-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
ConcurrentDictionary.cs
2754 lines (2447 loc) · 129 KB
/
ConcurrentDictionary.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>Represents a thread-safe collection of keys and values.</summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentDictionary{TKey,TValue}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> where TKey : notnull
{
/// <summary>Internal tables of the dictionary.</summary>
/// <remarks>
/// When using <see cref="_tables"/>, we must read the volatile _tables field into a local variable:
/// it is set to a new table on each table resize. Volatile.Reads on array elements then ensure that
/// we have a copy of the reference to tables._buckets[bucketNo]: this protects us from reading fields
/// ('_hashcode', '_key', '_value' and '_next') of different instances.
/// </remarks>
private volatile Tables _tables;
/// <summary>The maximum number of elements per lock before a resize operation is triggered.</summary>
private int _budget;
/// <summary>Whether to dynamically increase the size of the striped lock.</summary>
private readonly bool _growLockArray;
/// <summary>Whether a non-null comparer in <see cref="Tables._comparer"/> is the default comparer.</summary>
/// <remarks>
/// This is only used for reference types. It lets us use the key's GetHashCode directly rather than going indirectly
/// through the comparer. It can't be used for Equals, as the key might implement IEquatable and employ different
/// equality semantics than the virtual Equals, however unlikely that may be. This field enables us to save an
/// interface dispatch when using the default comparer with a non-string reference type key, at the expense of an
/// extra branch when using a custom comparer with a reference type key.
/// </remarks>
private readonly bool _comparerIsDefaultForClasses;
/// <summary>The initial size of the _buckets array.</summary>
/// <remarks>
/// We store this to retain the initially specified growing behavior of the _buckets array even after clearing the collection.
/// </remarks>
private readonly int _initialCapacity;
/// <summary>The default capacity, i.e. the initial # of buckets.</summary>
/// <remarks>
/// When choosing this value, we are making a trade-off between the size of a very small dictionary,
/// and the number of resizes when constructing a large dictionary.
/// </remarks>
private const int DefaultCapacity = 31;
/// <summary>
/// The maximum size of the striped lock that will not be exceeded when locks are automatically
/// added as the dictionary grows.
/// </summary>
/// <remarks>
/// The user is allowed to exceed this limit by passing
/// a concurrency level larger than MaxLockNumber into the constructor.
/// </remarks>
private const int MaxLockNumber = 1024;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that is empty, has the default concurrency level, has the default initial capacity, and
/// uses the default comparer for the key type.
/// </summary>
public ConcurrentDictionary()
: this(DefaultConcurrencyLevel, DefaultCapacity, growLockArray: true, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that is empty, has the specified concurrency level and capacity, and uses the default
/// comparer for the key type.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently, or -1 to indicate a default value.</param>
/// <param name="capacity">The initial number of elements that the <see cref="ConcurrentDictionary{TKey,TValue}"/> can contain.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is less than 1.</exception>
/// <exception cref="ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than 0.</exception>
public ConcurrentDictionary(int concurrencyLevel, int capacity)
: this(concurrencyLevel, capacity, growLockArray: false, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified <see cref="IEnumerable{T}"/>, has the default concurrency
/// level, has the default initial capacity, and uses the default comparer for the key type.
/// </summary>
/// <param name="collection">The <see
/// cref="IEnumerable{T}"/> whose elements are copied to the new <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentException"><paramref name="collection"/> contains one or more duplicate keys.</exception>
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection)
: this(DefaultConcurrencyLevel, collection, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that is empty, has the specified concurrency level and capacity, and uses the specified
/// <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
public ConcurrentDictionary(IEqualityComparer<TKey>? comparer)
: this(DefaultConcurrencyLevel, DefaultCapacity, growLockArray: true, comparer) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified <see cref="IEnumerable"/>, has the default concurrency
/// level, has the default initial capacity, and uses the specified <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="collection">The <see cref="IEnumerable{T}"/> whose elements are copied to the new <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference (Nothing in Visual Basic).</exception>
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer)
: this(DefaultConcurrencyLevel, GetCapacityFromCollection(collection), comparer)
{
ArgumentNullException.ThrowIfNull(collection);
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified <see cref="IEnumerable"/>,
/// has the specified concurrency level, has the specified initial capacity, and uses the specified
/// <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="concurrencyLevel">
/// The estimated number of threads that will update the <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently, or -1 to indicate a default value.
/// </param>
/// <param name="collection">The <see cref="IEnumerable{T}"/> whose elements are copied to the new
/// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is less than 1.</exception>
/// <exception cref="ArgumentException"><paramref name="collection"/> contains one or more duplicate keys.</exception>
public ConcurrentDictionary(int concurrencyLevel, IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer)
: this(concurrencyLevel, GetCapacityFromCollection(collection), growLockArray: false, comparer)
{
ArgumentNullException.ThrowIfNull(collection);
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that is empty, has the specified concurrency level, has the specified initial capacity, and
/// uses the specified <see cref="IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently, or -1 to indicate a default value.</param>
/// <param name="capacity">The initial number of elements that the <see cref="ConcurrentDictionary{TKey,TValue}"/> can contain.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing keys.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is less than 1. -or- <paramref name="capacity"/> is less than 0.</exception>
public ConcurrentDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TKey>? comparer)
: this(concurrencyLevel, capacity, growLockArray: false, comparer)
{
}
internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey>? comparer)
{
if (concurrencyLevel <= 0)
{
if (concurrencyLevel != -1)
{
throw new ArgumentOutOfRangeException(nameof(concurrencyLevel), SR.ConcurrentDictionary_ConcurrencyLevelMustBePositiveOrNegativeOne);
}
concurrencyLevel = DefaultConcurrencyLevel;
}
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
// The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
// any buckets. We also want it to be a prime.
if (capacity < concurrencyLevel)
{
capacity = concurrencyLevel;
}
capacity = HashHelpers.GetPrime(capacity);
var locks = new object[concurrencyLevel];
locks[0] = locks; // reuse array as the first lock object just to avoid an additional allocation
for (int i = 1; i < locks.Length; i++)
{
locks[i] = new object();
}
var countPerLock = new int[locks.Length];
var buckets = new VolatileNode[capacity];
// For reference types, we always want to store a comparer instance, either the one provided, or if
// one wasn't provided, the default (accessing EqualityComparer<TKey>.Default with shared generics
// on every dictionary access can add measurable overhead). For value types, if no comparer is provided,
// or if the default is provided, we'd prefer to use EqualityComparer<TKey>.Default.Equals/GetHashCode
// on every use, enabling the JIT to devirtualize and possibly inline the operation.
if (typeof(TKey).IsValueType)
{
if (comparer is not null && // first check for null to avoid forcing default comparer instantiation unnecessarily
ReferenceEquals(comparer, EqualityComparer<TKey>.Default))
{
comparer = null;
}
}
else
{
comparer ??= EqualityComparer<TKey>.Default;
// Special-case EqualityComparer<string>.Default, StringComparer.Ordinal, and StringComparer.OrdinalIgnoreCase.
// We use a non-randomized comparer for improved perf, falling back to a randomized comparer if the
// hash buckets become unbalanced.
if (typeof(TKey) == typeof(string) &&
NonRandomizedStringEqualityComparer.GetStringComparer(comparer) is IEqualityComparer<string> stringComparer)
{
comparer = (IEqualityComparer<TKey>)stringComparer;
}
else if (ReferenceEquals(comparer, EqualityComparer<TKey>.Default))
{
_comparerIsDefaultForClasses = true;
}
}
_tables = new Tables(buckets, locks, countPerLock, comparer);
_growLockArray = growLockArray;
_initialCapacity = capacity;
_budget = buckets.Length / locks.Length;
}
/// <summary>
/// Gets an instance of a type that may be used to perform operations on a <see cref="ConcurrentDictionary{TKey, TValue}"/>
/// using a <typeparamref name="TAlternateKey"/> as a key instead of a <typeparamref name="TKey"/>.
/// </summary>
/// <typeparam name="TAlternateKey">The alternate type of a key for performing lookups.</typeparam>
/// <returns>The created lookup instance.</returns>
/// <exception cref="InvalidOperationException">This instance's comparer is not compatible with <typeparamref name="TAlternateKey"/>.</exception>
/// <remarks>
/// This instance must be using a comparer that implements <see cref="IAlternateEqualityComparer{TAlternateKey, TKey}"/> with
/// <typeparamref name="TAlternateKey"/> and <typeparamref name="TKey"/>. If it doesn't, an exception will be thrown.
/// </remarks>
public AlternateLookup<TAlternateKey> GetAlternateLookup<TAlternateKey>() where TAlternateKey : notnull, allows ref struct
{
if (!IsCompatibleKey<TAlternateKey>(_tables))
{
ThrowHelper.ThrowIncompatibleComparer();
}
return new AlternateLookup<TAlternateKey>(this);
}
/// <summary>
/// Gets an instance of a type that may be used to perform operations on a <see cref="ConcurrentDictionary{TKey, TValue}"/>
/// using a <typeparamref name="TAlternateKey"/> as a key instead of a <typeparamref name="TKey"/>.
/// </summary>
/// <typeparam name="TAlternateKey">The alternate type of a key for performing lookups.</typeparam>
/// <param name="lookup">The created lookup instance when the method returns true, or a default instance that should not be used if the method returns false.</param>
/// <returns>true if a lookup could be created; otherwise, false.</returns>
/// <remarks>
/// This instance must be using a comparer that implements <see cref="IAlternateEqualityComparer{TAlternateKey, TKey}"/> with
/// <typeparamref name="TAlternateKey"/> and <typeparamref name="TKey"/>. If it doesn't, the method will return false.
/// </remarks>
public bool TryGetAlternateLookup<TAlternateKey>(out AlternateLookup<TAlternateKey> lookup) where TAlternateKey : notnull, allows ref struct
{
if (IsCompatibleKey<TAlternateKey>(_tables))
{
lookup = new AlternateLookup<TAlternateKey>(this);
return true;
}
lookup = default;
return false;
}
/// <summary>Computes an initial capacity to use based on an initial seed collection.</summary>
/// <param name="collection">The collection with which to initially populate this dictionary.</param>
/// <returns>The capacity to use.</returns>
/// <remarks>
/// Growing is expensive, and we don't know if the caller plans to add additional items beyond this
/// initial collection, so we use the maximum of the collection's size and the default capacity. That way,
/// the initial capacity selected isn't pessimized by seeding it with a collection that happens to be
/// smaller.
/// </remarks>
private static int GetCapacityFromCollection(IEnumerable<KeyValuePair<TKey, TValue>> collection) =>
collection switch
{
ICollection<KeyValuePair<TKey, TValue>> c => Math.Max(DefaultCapacity, c.Count),
IReadOnlyCollection<KeyValuePair<TKey, TValue>> rc => Math.Max(DefaultCapacity, rc.Count),
_ => DefaultCapacity,
};
/// <summary>Computes the hash code for the specified key using the dictionary's comparer.</summary>
/// <param name="comparer">
/// The comparer. It's passed in to avoid having to look it up via a volatile read on <see cref="_tables"/>;
/// such a comparer could also be incorrect if the table upgraded comparer concurrently.
/// </param>
/// <param name="key">The key for which to compute the hash code.</param>
/// <returns>The hash code of the key.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetHashCode(IEqualityComparer<TKey>? comparer, TKey key)
{
if (typeof(TKey).IsValueType)
{
return comparer is null ? key.GetHashCode() : comparer.GetHashCode(key);
}
Debug.Assert(comparer is not null);
return _comparerIsDefaultForClasses ? key.GetHashCode() : comparer.GetHashCode(key);
}
/// <summary>Determines whether the specified key and the key stored in the specified node are equal.</summary>
/// <param name="comparer">
/// The comparer. It's passed in to avoid having to look it up via a volatile read on <see cref="_tables"/>;
/// such a comparer could also be incorrect if the table upgraded comparer concurrently.
/// </param>
/// <param name="node">The node containing the key to compare.</param>
/// <param name="key">The other key to compare.</param>
/// <returns>true if the keys are equal; otherwise, false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool NodeEqualsKey(IEqualityComparer<TKey>? comparer, Node node, TKey key)
{
if (typeof(TKey).IsValueType)
{
return comparer is null ?
EqualityComparer<TKey>.Default.Equals(node._key, key) :
comparer.Equals(node._key, key);
}
Debug.Assert(comparer is not null);
return comparer.Equals(node._key, key);
}
private void InitializeFromCollection(IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
if (pair.Key is null)
{
ThrowHelper.ThrowKeyNullException();
}
if (!TryAddInternal(_tables, pair.Key, null, pair.Value, updateIfExists: false, acquireLock: false, out _))
{
throw new ArgumentException(SR.ConcurrentDictionary_SourceContainsDuplicateKeys);
}
}
if (_budget == 0)
{
Tables tables = _tables;
_budget = tables._buckets.Length / tables._locks.Length;
}
}
/// <summary>
/// Attempts to add the specified key and value to the <see cref="ConcurrentDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add. The value can be a null reference (Nothing
/// in Visual Basic) for reference types.</param>
/// <returns>
/// true if the key/value pair was added to the <see cref="ConcurrentDictionary{TKey, TValue}"/> successfully; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null reference (Nothing in Visual Basic).</exception>
/// <exception cref="OverflowException">The <see cref="ConcurrentDictionary{TKey, TValue}"/> contains too many elements.</exception>
public bool TryAdd(TKey key, TValue value)
{
if (key is null)
{
ThrowHelper.ThrowKeyNullException();
}
return TryAddInternal(_tables, key, null, value, updateIfExists: false, acquireLock: true, out _);
}
/// <summary>
/// Determines whether the <see cref="ConcurrentDictionary{TKey, TValue}"/> contains the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="ConcurrentDictionary{TKey, TValue}"/>.</param>
/// <returns>true if the <see cref="ConcurrentDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is a null reference (Nothing in Visual Basic).</exception>
public bool ContainsKey(TKey key) => TryGetValue(key, out _);
/// <summary>
/// Attempts to remove and return the value with the specified key from the <see cref="ConcurrentDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove and return.</param>
/// <param name="value">
/// When this method returns, <paramref name="value"/> contains the object removed from the
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> or the default value of <typeparamref
/// name="TValue"/> if the operation failed.
/// </param>
/// <returns>true if an object was removed successfully; otherwise, false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is a null reference (Nothing in Visual Basic).</exception>
public bool TryRemove(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key is null)
{
ThrowHelper.ThrowKeyNullException();
}
return TryRemoveInternal(key, out value, matchValue: false, default);
}
/// <summary>Removes a key and value from the dictionary.</summary>
/// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> representing the key and value to remove.</param>
/// <returns>
/// true if the key and value represented by <paramref name="item"/> are successfully
/// found and removed; otherwise, false.
/// </returns>
/// <remarks>
/// Both the specified key and value must match the entry in the dictionary for it to be removed.
/// The key is compared using the dictionary's comparer (or the default comparer for <typeparamref name="TKey"/>
/// if no comparer was provided to the dictionary when it was constructed). The value is compared using the
/// default comparer for <typeparamref name="TValue"/>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The <see cref="KeyValuePair{TKey, TValue}.Key"/> property of <paramref name="item"/> is a null reference.
/// </exception>
public bool TryRemove(KeyValuePair<TKey, TValue> item)
{
if (item.Key is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(item), SR.ConcurrentDictionary_ItemKeyIsNull);
}
return TryRemoveInternal(item.Key, out _, matchValue: true, item.Value);
}
/// <summary>
/// Removes the specified key from the dictionary if it exists and returns its associated value.
/// If matchValue flag is set, the key will be removed only if is associated with a particular
/// value.
/// </summary>
/// <param name="key">The key to search for and remove if it exists.</param>
/// <param name="value">The variable into which the removed value, if found, is stored.</param>
/// <param name="matchValue">Whether removal of the key is conditional on its value.</param>
/// <param name="oldValue">The conditional value to compare against if <paramref name="matchValue"/> is true</param>
private bool TryRemoveInternal(TKey key, [MaybeNullWhen(false)] out TValue value, bool matchValue, TValue? oldValue)
{
Tables tables = _tables;
IEqualityComparer<TKey>? comparer = tables._comparer;
int hashcode = GetHashCode(comparer, key);
while (true)
{
object[] locks = tables._locks;
ref Node? bucket = ref GetBucketAndLock(tables, hashcode, out uint lockNo);
lock (locks[lockNo])
{
// If the table just got resized, we may not be holding the right lock, and must retry.
// This should be a rare occurrence.
if (tables != _tables)
{
tables = _tables;
if (!ReferenceEquals(comparer, tables._comparer))
{
comparer = tables._comparer;
hashcode = GetHashCode(comparer, key);
}
continue;
}
Node? prev = null;
for (Node? curr = bucket; curr is not null; curr = curr._next)
{
Debug.Assert((prev is null && curr == bucket) || prev!._next == curr);
if (hashcode == curr._hashcode && NodeEqualsKey(comparer, curr, key))
{
if (matchValue)
{
bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr._value);
if (!valuesMatch)
{
value = default;
return false;
}
}
if (prev is null)
{
Volatile.Write(ref bucket, curr._next);
}
else
{
prev._next = curr._next;
}
value = curr._value;
tables._countPerLock[lockNo]--;
return true;
}
prev = curr;
}
}
value = default;
return false;
}
}
/// <summary>
/// Attempts to get the value associated with the specified key from the <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">
/// When this method returns, <paramref name="value"/> contains the object from
/// the <see cref="ConcurrentDictionary{TKey,TValue}"/> with the specified key or the default value of
/// <typeparamref name="TValue"/>, if the operation failed.
/// </param>
/// <returns>true if the key was found in the <see cref="ConcurrentDictionary{TKey,TValue}"/>; otherwise, false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is a null reference (Nothing in Visual Basic).</exception>
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key is null)
{
ThrowHelper.ThrowKeyNullException();
}
Tables tables = _tables;
IEqualityComparer<TKey>? comparer = tables._comparer;
if (typeof(TKey).IsValueType && // comparer can only be null for value types; enable JIT to eliminate entire if block for ref types
comparer is null)
{
int hashcode = key.GetHashCode();
for (Node? n = GetBucket(tables, hashcode); n is not null; n = n._next)
{
if (hashcode == n._hashcode && EqualityComparer<TKey>.Default.Equals(n._key, key))
{
value = n._value;
return true;
}
}
}
else
{
Debug.Assert(comparer is not null);
int hashcode = GetHashCode(comparer, key);
for (Node? n = GetBucket(tables, hashcode); n is not null; n = n._next)
{
if (hashcode == n._hashcode && comparer.Equals(n._key, key))
{
value = n._value;
return true;
}
}
}
value = default;
return false;
}
private static bool TryGetValueInternal(Tables tables, TKey key, int hashcode, [MaybeNullWhen(false)] out TValue value)
{
IEqualityComparer<TKey>? comparer = tables._comparer;
if (typeof(TKey).IsValueType && // comparer can only be null for value types; enable JIT to eliminate entire if block for ref types
comparer is null)
{
for (Node? n = GetBucket(tables, hashcode); n is not null; n = n._next)
{
if (hashcode == n._hashcode && EqualityComparer<TKey>.Default.Equals(n._key, key))
{
value = n._value;
return true;
}
}
}
else
{
Debug.Assert(comparer is not null);
for (Node? n = GetBucket(tables, hashcode); n is not null; n = n._next)
{
if (hashcode == n._hashcode && comparer.Equals(n._key, key))
{
value = n._value;
return true;
}
}
}
value = default;
return false;
}
/// <summary>
/// Updates the value associated with <paramref name="key"/> to <paramref name="newValue"/> if the existing value is equal
/// to <paramref name="comparisonValue"/>.
/// </summary>
/// <param name="key">The key whose value is compared with <paramref name="comparisonValue"/> and
/// possibly replaced.</param>
/// <param name="newValue">The value that replaces the value of the element with <paramref
/// name="key"/> if the comparison results in equality.</param>
/// <param name="comparisonValue">The value that is compared to the value of the element with
/// <paramref name="key"/>.</param>
/// <returns>
/// true if the value with <paramref name="key"/> was equal to <paramref name="comparisonValue"/> and
/// replaced with <paramref name="newValue"/>; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is a null reference.</exception>
public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
{
if (key is null)
{
ThrowHelper.ThrowKeyNullException();
}
return TryUpdateInternal(_tables, key, null, newValue, comparisonValue);
}
/// <summary>
/// Updates the value associated with <paramref name="key"/> to <paramref name="newValue"/> if the existing value is equal
/// to <paramref name="comparisonValue"/>.
/// </summary>
/// <param name="tables">The tables that were used to create the hash code.</param>
/// <param name="key">The key whose value is compared with <paramref name="comparisonValue"/> and
/// possibly replaced.</param>
/// <param name="nullableHashcode">The hashcode computed for <paramref name="key"/>.</param>
/// <param name="newValue">The value that replaces the value of the element with <paramref
/// name="key"/> if the comparison results in equality.</param>
/// <param name="comparisonValue">The value that is compared to the value of the element with
/// <paramref name="key"/>.</param>
/// <returns>
/// true if the value with <paramref name="key"/> was equal to <paramref name="comparisonValue"/> and
/// replaced with <paramref name="newValue"/>; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is a null reference.</exception>
private bool TryUpdateInternal(Tables tables, TKey key, int? nullableHashcode, TValue newValue, TValue comparisonValue)
{
IEqualityComparer<TKey>? comparer = tables._comparer;
int hashcode = nullableHashcode ?? GetHashCode(comparer, key);
Debug.Assert(nullableHashcode is null || nullableHashcode == hashcode);
EqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
while (true)
{
object[] locks = tables._locks;
ref Node? bucket = ref GetBucketAndLock(tables, hashcode, out uint lockNo);
lock (locks[lockNo])
{
// If the table just got resized, we may not be holding the right lock, and must retry.
// This should be a rare occurrence.
if (tables != _tables)
{
tables = _tables;
if (!ReferenceEquals(comparer, tables._comparer))
{
comparer = tables._comparer;
hashcode = GetHashCode(comparer, key);
}
continue;
}
// Try to find this key in the bucket
Node? prev = null;
for (Node? node = bucket; node is not null; node = node._next)
{
Debug.Assert((prev is null && node == bucket) || prev!._next == node);
if (hashcode == node._hashcode && NodeEqualsKey(comparer, node, key))
{
if (valueComparer.Equals(node._value, comparisonValue))
{
// Do the reference type check up front to handle many cases of shared generics.
// If TValue is a value type then the field's value here can be baked in. Otherwise,
// for the remaining shared generic cases the field access here would disqualify inlining,
// so the following check cannot be factored out of TryAddInternal/TryUpdateInternal.
if (!typeof(TValue).IsValueType || ConcurrentDictionaryTypeProps<TValue>.IsWriteAtomic)
{
node._value = newValue;
}
else
{
var newNode = new Node(node._key, newValue, hashcode, node._next);
if (prev is null)
{
Volatile.Write(ref bucket, newNode);
}
else
{
prev._next = newNode;
}
}
return true;
}
return false;
}
prev = node;
}
// didn't find the key
return false;
}
}
}
/// <summary>
/// Removes all keys and values from the <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
public void Clear()
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
// If the dictionary is already empty, then there's nothing to clear.
if (AreAllBucketsEmpty())
{
return;
}
Tables tables = _tables;
var newTables = new Tables(new VolatileNode[HashHelpers.GetPrime(_initialCapacity)], tables._locks, new int[tables._countPerLock.Length], tables._comparer);
_tables = newTables;
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
}
finally
{
ReleaseLocks(locksAcquired);
}
}
/// <summary>
/// Copies the elements of the <see cref="ICollection{T}"/> to an array of type <see cref="KeyValuePair{TKey,TValue}"/>,
/// starting at the specified array index.
/// </summary>
/// <param name="array">
/// The one-dimensional array of type <see cref="KeyValuePair{TKey,TValue}"/> that is the destination of the <see
/// cref="KeyValuePair{TKey,TValue}"/> elements copied from the <see cref="ICollection"/>. The array must have zero-based indexing.
/// </param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>. -or- The number of
/// elements in the source <see cref="ICollection"/> is greater than the available space from <paramref name="index"/> to
/// the end of the destination <paramref name="array"/>.
/// </exception>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
ArgumentNullException.ThrowIfNull(array);
ArgumentOutOfRangeException.ThrowIfNegative(index);
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
int count = GetCountNoLocks();
if (array.Length - count < index)
{
throw new ArgumentException(SR.ConcurrentDictionary_ArrayNotLargeEnough);
}
CopyToPairs(array, index);
}
finally
{
ReleaseLocks(locksAcquired);
}
}
/// <summary>
/// Copies the key and value pairs stored in the <see cref="ConcurrentDictionary{TKey,TValue}"/> to a
/// new array.
/// </summary>
/// <returns>A new array containing a snapshot of key and value pairs copied from the <see cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </returns>
public KeyValuePair<TKey, TValue>[] ToArray()
{
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
int count = GetCountNoLocks();
if (count == 0)
{
return Array.Empty<KeyValuePair<TKey, TValue>>();
}
var array = new KeyValuePair<TKey, TValue>[count];
CopyToPairs(array, 0);
return array;
}
finally
{
ReleaseLocks(locksAcquired);
}
}
/// <summary>Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.</summary>
/// <remarks>Important: the caller must hold all locks in _locks before calling CopyToPairs.</remarks>
private void CopyToPairs(KeyValuePair<TKey, TValue>[] array, int index)
{
foreach (VolatileNode bucket in _tables._buckets)
{
for (Node? current = bucket._node; current is not null; current = current._next)
{
array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
Debug.Assert(index < int.MaxValue, "This method should only be called when there's no overflow risk");
index++;
}
}
}
/// <summary>Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.</summary>
/// <remarks>Important: the caller must hold all locks in _locks before calling CopyToPairs.</remarks>
private void CopyToEntries(DictionaryEntry[] array, int index)
{
foreach (VolatileNode bucket in _tables._buckets)
{
for (Node? current = bucket._node; current is not null; current = current._next)
{
array[index] = new DictionaryEntry(current._key, current._value);
Debug.Assert(index < int.MaxValue, "This method should only be called when there's no overflow risk");
index++;
}
}
}
/// <summary>Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.</summary>
/// <remarks>Important: the caller must hold all locks in _locks before calling CopyToPairs.</remarks>
private void CopyToObjects(object[] array, int index)
{
foreach (VolatileNode bucket in _tables._buckets)
{
for (Node? current = bucket._node; current is not null; current = current._next)
{
array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
Debug.Assert(index < int.MaxValue, "This method should only be called when there's no overflow risk");
index++;
}
}
}
/// <summary>Returns an enumerator that iterates through the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.</summary>
/// <returns>An enumerator for the <see cref="ConcurrentDictionary{TKey,TValue}"/>.</returns>
/// <remarks>
/// The enumerator returned from the dictionary is safe to use concurrently with
/// reads and writes to the dictionary, however it does not represent a moment-in-time snapshot
/// of the dictionary. The contents exposed through the enumerator may contain modifications
/// made to the dictionary after <see cref="GetEnumerator"/> was called.
/// </remarks>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => new Enumerator(this);
/// <summary>Provides an enumerator implementation for the dictionary.</summary>
private sealed class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
// Provides a manually-implemented version of (approximately) this iterator:
// VolatileNodeWrapper[] buckets = _tables._buckets;
// for (int i = 0; i < buckets.Length; i++)
// for (Node? current = buckets[i]._node; current is not null; current = current._next)
// yield return new KeyValuePair<TKey, TValue>(current._key, current._value);
private readonly ConcurrentDictionary<TKey, TValue> _dictionary;
private ConcurrentDictionary<TKey, TValue>.VolatileNode[]? _buckets;
private Node? _node;
private int _i;
private int _state;
private const int StateUninitialized = 0;
private const int StateOuterloop = 1;
private const int StateInnerLoop = 2;
private const int StateDone = 3;
public Enumerator(ConcurrentDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_i = -1;
}
public KeyValuePair<TKey, TValue> Current { get; private set; }
object IEnumerator.Current => Current;
public void Reset()
{
_buckets = null;
_node = null;
Current = default;
_i = -1;
_state = StateUninitialized;
}
public void Dispose() { }
public bool MoveNext()
{
switch (_state)
{
case StateUninitialized:
_buckets = _dictionary._tables._buckets;
_i = -1;
goto case StateOuterloop;
case StateOuterloop:
ConcurrentDictionary<TKey, TValue>.VolatileNode[]? buckets = _buckets;
Debug.Assert(buckets is not null);
int i = ++_i;
if ((uint)i < (uint)buckets.Length)
{
_node = buckets[i]._node;
_state = StateInnerLoop;
goto case StateInnerLoop;
}
goto default;
case StateInnerLoop:
if (_node is Node node)
{
Current = new KeyValuePair<TKey, TValue>(node._key, node._value);
_node = node._next;
return true;
}
goto case StateOuterloop;
default:
_state = StateDone;
return false;
}
}
}
/// <summary>
/// Shared internal implementation for inserts and updates.
/// If key exists, we always return false; and if updateIfExists == true we force update with value;
/// If key doesn't exist, we always add value and return true;
/// </summary>
private bool TryAddInternal(Tables tables, TKey key, int? nullableHashcode, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
{
IEqualityComparer<TKey>? comparer = tables._comparer;
int hashcode = nullableHashcode ?? GetHashCode(comparer, key);
Debug.Assert(nullableHashcode is null || nullableHashcode == hashcode);
while (true)
{
object[] locks = tables._locks;
ref Node? bucket = ref GetBucketAndLock(tables, hashcode, out uint lockNo);
bool resizeDesired = false;
bool forceRehash = false;
bool lockTaken = false;
try
{
if (acquireLock)
{
Monitor.Enter(locks[lockNo], ref lockTaken);
}
// If the table just got resized, we may not be holding the right lock, and must retry.
// This should be a rare occurrence.
if (tables != _tables)
{
tables = _tables;
if (!ReferenceEquals(comparer, tables._comparer))
{
comparer = tables._comparer;
hashcode = GetHashCode(comparer, key);
}
continue;
}
// Try to find this key in the bucket
uint collisionCount = 0;
Node? prev = null;
for (Node? node = bucket; node is not null; node = node._next)
{
Debug.Assert((prev is null && node == bucket) || prev!._next == node);
if (hashcode == node._hashcode && NodeEqualsKey(comparer, node, key))
{
// The key was found in the dictionary. If updates are allowed, update the value for that key.
// We need to create a new node for the update, in order to support TValue types that cannot
// be written atomically, since lock-free reads may be happening concurrently.
if (updateIfExists)
{
// Do the reference type check up front to handle many cases of shared generics.
// If TValue is a value type then the field's value here can be baked in. Otherwise,
// for the remaining shared generic cases the field access here would disqualify inlining,
// so the following check cannot be factored out of TryAddInternal/TryUpdateInternal.
if (!typeof(TValue).IsValueType || ConcurrentDictionaryTypeProps<TValue>.IsWriteAtomic)
{
node._value = value;