This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
ConcurrentDictionary.cs
2077 lines (1857 loc) · 92.4 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.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Class: ConcurrentDictionary
**
**
** Purpose: A scalable dictionary for concurrent access
**
**
===========================================================*/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
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>
{
/// <summary>
/// Tables that hold the internal state of the ConcurrentDictionary
///
/// Wrapping the three tables in a single object allows us to atomically
/// replace all tables at once.
/// </summary>
private sealed class Tables
{
internal readonly Node[] _buckets; // A singly-linked list for each bucket.
internal readonly object[] _locks; // A set of locks, each guarding a section of the table.
internal volatile int[] _countPerLock; // The number of elements guarded by each lock.
internal Tables(Node[] buckets, object[] locks, int[] countPerLock)
{
_buckets = buckets;
_locks = locks;
_countPerLock = countPerLock;
}
}
private volatile Tables _tables; // Internal tables of the dictionary
private IEqualityComparer<TKey> _comparer; // Key equality comparer
private readonly bool _growLockArray; // Whether to dynamically increase the size of the striped lock
private int _budget; // The maximum number of elements per lock before a resize operation is triggered
// The default capacity, i.e. the initial # of buckets. 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. Also, the capacity should not be divisible by a small prime.
private const int DefaultCapacity = 31;
// The maximum size of the striped lock that will not be exceeded when locks are automatically
// added as the dictionary grows. However, the user is allowed to exceed this limit by passing
// a concurrency level larger than MaxLockNumber into the constructor.
private const int MaxLockNumber = 1024;
// Whether TValue is a type that can be written atomically (i.e., with no danger of torn reads)
private static readonly bool s_isValueWriteAtomic = IsValueWriteAtomic();
/// <summary>
/// Determines whether type TValue can be written atomically
/// </summary>
private static bool IsValueWriteAtomic()
{
//
// Section 12.6.6 of ECMA CLI explains which types can be read and written atomically without
// the risk of tearing.
//
// See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf
//
Type valueType = typeof(TValue);
if (!valueType.IsValueType)
{
return true;
}
switch (Type.GetTypeCode(valueType))
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
return true;
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.UInt64:
return IntPtr.Size == 8;
default:
return false;
}
}
/// <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, 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.</param>
/// <param name="capacity">The initial number of elements that the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>
/// can contain.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is
/// less than 1.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than
/// 0.</exception>
public ConcurrentDictionary(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, false, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified <see
/// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/>, 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="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
/// the new
/// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.ArgumentException"><paramref name="collection"/> contains one or more
/// duplicate keys.</exception>
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(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="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
/// implementation to use when comparing keys.</param>
public ConcurrentDictionary(IEqualityComparer<TKey> comparer) : this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// class that contains elements copied from the specified <see
/// cref="T:System.Collections.IEnumerable"/>, has the default concurrency level, has the default
/// initial capacity, and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="collection">The <see
/// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
/// the new
/// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
/// implementation to use when comparing keys.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
: this(comparer)
{
if (collection == null) throw new ArgumentNullException(nameof(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="T:System.Collections.IEnumerable"/>,
/// has the specified concurrency level, has the specified initial capacity, and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
/// <param name="collection">The <see cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to the new
/// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/> implementation to use
/// when comparing keys.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is a null reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="concurrencyLevel"/> is less than 1.
/// </exception>
/// <exception cref="T:System.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, DefaultCapacity, false, comparer)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
InitializeFromCollection(collection);
}
private void InitializeFromCollection(IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
TValue dummy;
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
if (pair.Key == null) ThrowKeyNullException();
if (!TryAddInternal(pair.Key, _comparer.GetHashCode(pair.Key), pair.Value, false, false, out dummy))
{
throw new ArgumentException(SR.ConcurrentDictionary_SourceContainsDuplicateKeys);
}
}
if (_budget == 0)
{
_budget = _tables._buckets.Length / _tables._locks.Length;
}
}
/// <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="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</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="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
/// implementation to use when comparing keys.</param>
/// <exception cref="T:System.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, false, comparer)
{
}
internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer)
{
if (concurrencyLevel < 1)
{
throw new ArgumentOutOfRangeException(nameof(concurrencyLevel), SR.ConcurrentDictionary_ConcurrencyLevelMustBePositive);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ConcurrentDictionary_CapacityMustNotBeNegative);
}
// The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
// any buckets.
if (capacity < concurrencyLevel)
{
capacity = concurrencyLevel;
}
object[] locks = new object[concurrencyLevel];
for (int i = 0; i < locks.Length; i++)
{
locks[i] = new object();
}
int[] countPerLock = new int[locks.Length];
Node[] buckets = new Node[capacity];
_tables = new Tables(buckets, locks, countPerLock);
_comparer = comparer ?? EqualityComparer<TKey>.Default;
_growLockArray = growLockArray;
_budget = buckets.Length / 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="T:System.ArgumentNullException"><paramref name="key"/> is null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.OverflowException">The <see cref="ConcurrentDictionary{TKey, TValue}"/>
/// contains too many elements.</exception>
public bool TryAdd(TKey key, TValue value)
{
if (key == null) ThrowKeyNullException();
TValue dummy;
return TryAddInternal(key, _comparer.GetHashCode(key), value, false, true, out dummy);
}
/// <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="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public bool ContainsKey(TKey key)
{
if (key == null) ThrowKeyNullException();
TValue throwAwayValue;
return TryGetValue(key, out throwAwayValue);
}
/// <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="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public bool TryRemove(TKey key, out TValue value)
{
if (key == null) ThrowKeyNullException();
return TryRemoveInternal(key, out value, false, default(TValue));
}
/// <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>
/// <returns></returns>
private bool TryRemoveInternal(TKey key, out TValue value, bool matchValue, TValue oldValue)
{
int hashcode = _comparer.GetHashCode(key);
while (true)
{
Tables tables = _tables;
int bucketNo, lockNo;
GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
lock (tables._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)
{
continue;
}
Node prev = null;
for (Node curr = tables._buckets[bucketNo]; curr != null; curr = curr._next)
{
Debug.Assert((prev == null && curr == tables._buckets[bucketNo]) || prev._next == curr);
if (hashcode == curr._hashcode && _comparer.Equals(curr._key, key))
{
if (matchValue)
{
bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr._value);
if (!valuesMatch)
{
value = default(TValue);
return false;
}
}
if (prev == null)
{
Volatile.Write<Node>(ref tables._buckets[bucketNo], curr._next);
}
else
{
prev._next = curr._next;
}
value = curr._value;
tables._countPerLock[lockNo]--;
return true;
}
prev = curr;
}
}
value = default(TValue);
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="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null) ThrowKeyNullException();
return TryGetValueInternal(key, _comparer.GetHashCode(key), out value);
}
private bool TryGetValueInternal(TKey key, int hashcode, out TValue value)
{
Debug.Assert(_comparer.GetHashCode(key) == hashcode);
// We must capture the _buckets field in a local variable. It is set to a new table on each table resize.
Tables tables = _tables;
int bucketNo = GetBucket(hashcode, tables._buckets.Length);
// We can get away w/out a lock here.
// The Volatile.Read ensures 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.
Node n = Volatile.Read<Node>(ref tables._buckets[bucketNo]);
while (n != null)
{
if (hashcode == n._hashcode && _comparer.Equals(n._key, key))
{
value = n._value;
return true;
}
n = n._next;
}
value = default(TValue);
return false;
}
/// <summary>
/// Compares the existing value for the specified key with a specified value, and if they're equal,
/// updates the key with a third value.
/// </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="T:System.ArgumentNullException"><paramref name="key"/> is a null
/// reference.</exception>
public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
{
if (key == null) ThrowKeyNullException();
return TryUpdateInternal(key, _comparer.GetHashCode(key), newValue, comparisonValue);
}
/// <summary>
/// Compares the existing value for the specified key with a specified value, and if they're equal,
/// updates the key with a third value.
/// </summary>
/// <param name="key">The key whose value is compared with <paramref name="comparisonValue"/> and
/// possibly replaced.</param>
/// <param name="hashcode">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="T:System.ArgumentNullException"><paramref name="key"/> is a null
/// reference.</exception>
private bool TryUpdateInternal(TKey key, int hashcode, TValue newValue, TValue comparisonValue)
{
Debug.Assert(_comparer.GetHashCode(key) == hashcode);
IEqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
while (true)
{
int bucketNo;
int lockNo;
Tables tables = _tables;
GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
lock (tables._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)
{
continue;
}
// Try to find this key in the bucket
Node prev = null;
for (Node node = tables._buckets[bucketNo]; node != null; node = node._next)
{
Debug.Assert((prev == null && node == tables._buckets[bucketNo]) || prev._next == node);
if (hashcode == node._hashcode && _comparer.Equals(node._key, key))
{
if (valueComparer.Equals(node._value, comparisonValue))
{
if (s_isValueWriteAtomic)
{
node._value = newValue;
}
else
{
Node newNode = new Node(node._key, newValue, hashcode, node._next);
if (prev == null)
{
Volatile.Write(ref tables._buckets[bucketNo], 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);
Tables newTables = new Tables(new Node[DefaultCapacity], _tables._locks, new int[_tables._countPerLock.Length]);
_tables = newTables;
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection"/> to an array of
/// type <see cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>, starting at the
/// specified array index.
/// </summary>
/// <param name="array">The one-dimensional array of type <see
/// cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>
/// that is the destination of the <see
/// cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/> elements copied from the <see
/// cref="T:System.Collections.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="T:System.ArgumentNullException"><paramref name="array"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// 0.</exception>
/// <exception cref="T:System.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="T:System.Collections.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)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative);
int locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
int count = 0;
for (int i = 0; i < _tables._locks.Length && count >= 0; i++)
{
count += _tables._countPerLock[i];
}
if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
{
throw new ArgumentException(SR.ConcurrentDictionary_ArrayNotLargeEnough);
}
CopyToPairs(array, index);
}
finally
{
ReleaseLocks(0, 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 = 0;
checked
{
for (int i = 0; i < _tables._locks.Length; i++)
{
count += _tables._countPerLock[i];
}
}
if (count == 0)
{
return Array.Empty<KeyValuePair<TKey, TValue>>();
}
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];
CopyToPairs(array, 0);
return array;
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
/// Important: the caller must hold all locks in _locks before calling CopyToPairs.
/// </summary>
private void CopyToPairs(KeyValuePair<TKey, TValue>[] array, int index)
{
Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
for (Node current = buckets[i]; current != null; current = current._next)
{
array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
index++; //this should never flow, CopyToPairs is only called when there's no overflow risk
}
}
}
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
/// Important: the caller must hold all locks in _locks before calling CopyToEntries.
/// </summary>
private void CopyToEntries(DictionaryEntry[] array, int index)
{
Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
for (Node current = buckets[i]; current != null; current = current._next)
{
array[index] = new DictionaryEntry(current._key, current._value);
index++; //this should never flow, CopyToEntries is only called when there's no overflow risk
}
}
}
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
/// Important: the caller must hold all locks in _locks before calling CopyToObjects.
/// </summary>
private void CopyToObjects(object[] array, int index)
{
Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
for (Node current = buckets[i]; current != null; current = current._next)
{
array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
index++; //this should never flow, CopyToObjects is only called when there's no overflow risk
}
}
}
/// <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()
{
Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
// The Volatile.Read ensures that we have a copy of the reference to buckets[i].
// This protects us from reading fields ('_key', '_value' and '_next') of different instances.
Node current = Volatile.Read<Node>(ref buckets[i]);
while (current != null)
{
yield return new KeyValuePair<TKey, TValue>(current._key, current._value);
current = current._next;
}
}
}
/// <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(TKey key, int hashcode, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
{
Debug.Assert(_comparer.GetHashCode(key) == hashcode);
while (true)
{
int bucketNo, lockNo;
Tables tables = _tables;
GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
bool resizeDesired = false;
bool lockTaken = false;
try
{
if (acquireLock)
Monitor.Enter(tables._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)
{
continue;
}
// Try to find this key in the bucket
Node prev = null;
for (Node node = tables._buckets[bucketNo]; node != null; node = node._next)
{
Debug.Assert((prev == null && node == tables._buckets[bucketNo]) || prev._next == node);
if (hashcode == node._hashcode && _comparer.Equals(node._key, 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)
{
if (s_isValueWriteAtomic)
{
node._value = value;
}
else
{
Node newNode = new Node(node._key, value, hashcode, node._next);
if (prev == null)
{
Volatile.Write(ref tables._buckets[bucketNo], newNode);
}
else
{
prev._next = newNode;
}
}
resultingValue = value;
}
else
{
resultingValue = node._value;
}
return false;
}
prev = node;
}
// The key was not found in the bucket. Insert the key-value pair.
Volatile.Write<Node>(ref tables._buckets[bucketNo], new Node(key, value, hashcode, tables._buckets[bucketNo]));
checked
{
tables._countPerLock[lockNo]++;
}
//
// If the number of elements guarded by this lock has exceeded the budget, resize the bucket table.
// It is also possible that GrowTable will increase the budget but won't resize the bucket table.
// That happens if the bucket table is found to be poorly utilized due to a bad hash function.
//
if (tables._countPerLock[lockNo] > _budget)
{
resizeDesired = true;
}
}
finally
{
if (lockTaken)
Monitor.Exit(tables._locks[lockNo]);
}
//
// The fact that we got here means that we just performed an insertion. If necessary, we will grow the table.
//
// Concurrency notes:
// - Notice that we are not holding any locks at when calling GrowTable. This is necessary to prevent deadlocks.
// - As a result, it is possible that GrowTable will be called unnecessarily. But, GrowTable will obtain lock 0
// and then verify that the table we passed to it as the argument is still the current table.
//
if (resizeDesired)
{
GrowTable(tables);
}
resultingValue = value;
return true;
}
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <value>The value associated with the specified key. If the specified key is not found, a get
/// operation throws a
/// <see cref="T:System.Collections.Generic.KeyNotFoundException"/>, and a set operation creates a new
/// element with the specified key.</value>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and
/// <paramref name="key"/>
/// does not exist in the collection.</exception>
public TValue this[TKey key]
{
get
{
TValue value;
if (!TryGetValue(key, out value))
{
ThrowKeyNotFoundException();
}
return value;
}
set
{
if (key == null) ThrowKeyNullException();
TValue dummy;
TryAddInternal(key, _comparer.GetHashCode(key), value, true, true, out dummy);
}
}
// These exception throwing sites have been extracted into their own NoInlining methods
// as these are uncommonly needed and when inlined are observed to prevent the inlining
// of important methods like TryGetValue and ContainsKey.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowKeyNotFoundException()
{
throw new KeyNotFoundException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowKeyNullException()
{
throw new ArgumentNullException("key");
}
/// <summary>
/// Gets the number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <exception cref="T:System.OverflowException">The dictionary contains too many
/// elements.</exception>
/// <value>The number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.</value>
/// <remarks>Count has snapshot semantics and represents the number of items in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>
/// at the moment when Count was accessed.</remarks>
public int Count
{
get
{
int acquiredLocks = 0;
try
{
// Acquire all locks
AcquireAllLocks(ref acquiredLocks);
return GetCountInternal();
}
finally
{
// Release locks that have been acquired earlier
ReleaseLocks(0, acquiredLocks);
}
}
}
/// <summary>
/// Gets the number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>. Should only be used after all locks
/// have been acquired.
/// </summary>
/// <exception cref="T:System.OverflowException">The dictionary contains too many
/// elements.</exception>
/// <value>The number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.</value>
/// <remarks>Count has snapshot semantics and represents the number of items in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>
/// at the moment when Count was accessed.</remarks>
private int GetCountInternal()
{
int count = 0;
// Compute the count, we allow overflow
for (int i = 0; i < _tables._countPerLock.Length; i++)
{
count += _tables._countPerLock[i];
}
return count;
}
/// <summary>
/// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// if the key does not already exist.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="valueFactory">The function used to generate a value for the key</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="valueFactory"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.OverflowException">The dictionary contains too many
/// elements.</exception>
/// <returns>The value for the key. This will be either the existing value for the key if the
/// key is already in the dictionary, or the new value for the key as returned by valueFactory
/// if the key was not in the dictionary.</returns>
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
if (key == null) ThrowKeyNullException();
if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory));
int hashcode = _comparer.GetHashCode(key);
TValue resultingValue;
if (!TryGetValueInternal(key, hashcode, out resultingValue))
{
TryAddInternal(key, hashcode, valueFactory(key), false, true, out resultingValue);
}
return resultingValue;
}
/// <summary>
/// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
/// if the key does not already exist.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="valueFactory">The function used to generate a value for the key</param>
/// <param name="factoryArgument">An argument value to pass into <paramref name="valueFactory"/>.</param>