Debian Codegraph @

mcs/class/referencesource/mscorlib/system/collections/Concurrent/ConcurrentDictionary.cs

raw
1 // ==++==
2 //
3 // Copyright (c) Microsoft Corporation. All rights reserved.
4 //
5 // ==--==
6 //
7 // <OWNER>Microsoft</OWNER>
8 /*============================================================
9 **
10 ** Class: ConcurrentDictionary
11 **
12 **
13 ** Purpose: A scalable dictionary for concurrent access
14 **
15 **
16 ===========================================================*/
17
18 // If CDS_COMPILE_JUST_THIS symbol is defined, the ConcurrentDictionary.cs file compiles separately,
19 // with no dependencies other than .NET Framework 3.5.
20
21 //#define CDS_COMPILE_JUST_THIS
22
23 using System;
24 using System.Collections.Generic;
25 using System.Text;
26 using System.Threading;
27 using System.Runtime.InteropServices;
28 using System.Diagnostics;
29 using System.Collections;
30 using System.Runtime.Serialization;
31 using System.Security;
32 using System.Security.Permissions;
33 using System.Collections.ObjectModel;
34
35 #if !CDS_COMPILE_JUST_THIS
36 using System.Diagnostics.Contracts;
37 #endif
38
39 using System.Diagnostics.CodeAnalysis;
40
41 namespace System.Collections.Concurrent
42 {
43
44 /// <summary>
45 /// Represents a thread-safe collection of keys and values.
46 /// </summary>
47 /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
48 /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
49 /// <remarks>
50 /// All public and protected members of <see cref="ConcurrentDictionary{TKey,TValue}"/> are thread-safe and may be used
51 /// concurrently from multiple threads.
52 /// </remarks>
53 #if !FEATURE_CORECLR
54 [Serializable]
55 #endif
56 [ComVisible(false)]
57 [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
58 [DebuggerDisplay("Count = {Count}")]
59 [HostProtection(Synchronization = true, ExternalThreading = true)]
60 public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
61 {
62 /// <summary>
63 /// Tables that hold the internal state of the ConcurrentDictionary
64 ///
65 /// Wrapping the three tables in a single object allows us to atomically
66 /// replace all tables at once.
67 /// </summary>
68 private class Tables
69 {
70 internal readonly Node[] m_buckets; // A singly-linked list for each bucket.
71 internal readonly object[] m_locks; // A set of locks, each guarding a section of the table.
72 internal volatile int[] m_countPerLock; // The number of elements guarded by each lock.
73 internal readonly IEqualityComparer<TKey> m_comparer; // Key equality comparer
74
75 internal Tables(Node[] buckets, object[] locks, int[] countPerLock, IEqualityComparer<TKey> comparer)
76 {
77 m_buckets = buckets;
78 m_locks = locks;
79 m_countPerLock = countPerLock;
80 m_comparer = comparer;
81 }
82 }
83 #if !FEATURE_CORECLR
84 [NonSerialized]
85 #endif
86 private volatile Tables m_tables; // Internal tables of the dictionary
87 // NOTE: this is only used for compat reasons to serialize the comparer.
88 // This should not be accessed from anywhere else outside of the serialization methods.
89 internal IEqualityComparer<TKey> m_comparer;
90 #if !FEATURE_CORECLR
91 [NonSerialized]
92 #endif
93 private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock
94
95 // How many times we resized becaused of collisions.
96 // This is used to make sure we don't resize the dictionary because of multi-threaded Add() calls
97 // that generate collisions. Whenever a GrowTable() should be the only place that changes this
98 #if !FEATURE_CORECLR
99 // The field should be have been marked as NonSerialized but because we shipped it without that attribute in 4.5.1.
100 // we can't add it back without breaking compat. To maximize compat we are going to keep the OptionalField attribute
101 // This will prevent cases where the field was not serialized.
102 [OptionalField]
103 #endif
104 private int m_keyRehashCount;
105
106 #if !FEATURE_CORECLR
107 [NonSerialized]
108 #endif
109 private int m_budget; // The maximum number of elements per lock before a resize operation is triggered
110
111 #if !FEATURE_CORECLR // These fields are not used in CoreCLR
112 private KeyValuePair<TKey, TValue>[] m_serializationArray; // Used for custom serialization
113
114 private int m_serializationConcurrencyLevel; // used to save the concurrency level in serialization
115
116 private int m_serializationCapacity; // used to save the capacity in serialization
117 #endif
118 // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
119 // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
120 // and blocking, but also the more expensive operations that require all locks become (e.g. table
121 // resizing, ToArray, Count, etc). According to brief benchmarks that we ran, 4 seems like a good
122 // compromise.
123 private const int DEFAULT_CONCURRENCY_MULTIPLIER = 4;
124
125 // The default capacity, i.e. the initial # of buckets. When choosing this value, we are making
126 // a trade-off between the size of a very small dictionary, and the number of resizes when
127 // constructing a large dictionary. Also, the capacity should not be divisible by a small prime.
128 private const int DEFAULT_CAPACITY = 31;
129
130 // The maximum size of the striped lock that will not be exceeded when locks are automatically
131 // added as the dictionary grows. However, the user is allowed to exceed this limit by passing
132 // a concurrency level larger than MAX_LOCK_NUMBER into the constructor.
133 private const int MAX_LOCK_NUMBER = 1024;
134
135 // Whether TValue is a type that can be written atomically (i.e., with no danger of torn reads)
136 private static readonly bool s_isValueWriteAtomic = IsValueWriteAtomic();
137
138
139 /// <summary>
140 /// Determines whether type TValue can be written atomically
141 /// </summary>
142 private static bool IsValueWriteAtomic()
143 {
144 Type valueType = typeof(TValue);
145
146 //
147 // Section 12.6.6 of ECMA CLI explains which types can be read and written atomically without
148 // the risk of tearing.
149 //
150 // See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf
151 //
152 bool isAtomic =
153 (valueType.IsClass)
154 || valueType == typeof(Boolean)
155 || valueType == typeof(Char)
156 || valueType == typeof(Byte)
157 || valueType == typeof(SByte)
158 || valueType == typeof(Int16)
159 || valueType == typeof(UInt16)
160 || valueType == typeof(Int32)
161 || valueType == typeof(UInt32)
162 || valueType == typeof(Single);
163
164 if (!isAtomic && IntPtr.Size == 8)
165 {
166 isAtomic |= valueType == typeof(Double) || valueType == typeof(Int64);
167 }
168
169 return isAtomic;
170 }
171
172 /// <summary>
173 /// Initializes a new instance of the <see
174 /// cref="ConcurrentDictionary{TKey,TValue}"/>
175 /// class that is empty, has the default concurrency level, has the default initial capacity, and
176 /// uses the default comparer for the key type.
177 /// </summary>
178 public ConcurrentDictionary() : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, EqualityComparer<TKey>.Default) { }
179
180 /// <summary>
181 /// Initializes a new instance of the <see
182 /// cref="ConcurrentDictionary{TKey,TValue}"/>
183 /// class that is empty, has the specified concurrency level and capacity, and uses the default
184 /// comparer for the key type.
185 /// </summary>
186 /// <param name="concurrencyLevel">The estimated number of threads that will update the
187 /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
188 /// <param name="capacity">The initial number of elements that the <see
189 /// cref="ConcurrentDictionary{TKey,TValue}"/>
190 /// can contain.</param>
191 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is
192 /// less than 1.</exception>
193 /// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than
194 /// 0.</exception>
195 public ConcurrentDictionary(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, false, EqualityComparer<TKey>.Default) { }
196
197 /// <summary>
198 /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
199 /// class that contains elements copied from the specified <see
200 /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/>, has the default concurrency
201 /// level, has the default initial capacity, and uses the default comparer for the key type.
202 /// </summary>
203 /// <param name="collection">The <see
204 /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
205 /// the new
206 /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
207 /// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
208 /// (Nothing in Visual Basic).</exception>
209 /// <exception cref="T:System.ArgumentException"><paramref name="collection"/> contains one or more
210 /// duplicate keys.</exception>
211 public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, EqualityComparer<TKey>.Default) { }
212
213 /// <summary>
214 /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
215 /// class that is empty, has the specified concurrency level and capacity, and uses the specified
216 /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
217 /// </summary>
218 /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
219 /// implementation to use when comparing keys.</param>
220 /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference
221 /// (Nothing in Visual Basic).</exception>
222 public ConcurrentDictionary(IEqualityComparer<TKey> comparer) : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, comparer) { }
223
224 /// <summary>
225 /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
226 /// class that contains elements copied from the specified <see
227 /// cref="T:System.Collections.IEnumerable"/>, has the default concurrency level, has the default
228 /// initial capacity, and uses the specified
229 /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
230 /// </summary>
231 /// <param name="collection">The <see
232 /// cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to
233 /// the new
234 /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
235 /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
236 /// implementation to use when comparing keys.</param>
237 /// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
238 /// (Nothing in Visual Basic). -or-
239 /// <paramref name="comparer"/> is a null reference (Nothing in Visual Basic).
240 /// </exception>
241 public ConcurrentDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
242 : this(comparer)
243 {
244 if (collection == null) throw new ArgumentNullException("collection");
245
246 InitializeFromCollection(collection);
247 }
248
249 /// <summary>
250 /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
251 /// class that contains elements copied from the specified <see cref="T:System.Collections.IEnumerable"/>,
252 /// has the specified concurrency level, has the specified initial capacity, and uses the specified
253 /// <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
254 /// </summary>
255 /// <param name="concurrencyLevel">The estimated number of threads that will update the
256 /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
257 /// <param name="collection">The <see cref="T:System.Collections.IEnumerable{KeyValuePair{TKey,TValue}}"/> whose elements are copied to the new
258 /// <see cref="ConcurrentDictionary{TKey,TValue}"/>.</param>
259 /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/> implementation to use
260 /// when comparing keys.</param>
261 /// <exception cref="T:System.ArgumentNullException">
262 /// <paramref name="collection"/> is a null reference (Nothing in Visual Basic).
263 /// -or-
264 /// <paramref name="comparer"/> is a null reference (Nothing in Visual Basic).
265 /// </exception>
266 /// <exception cref="T:System.ArgumentOutOfRangeException">
267 /// <paramref name="concurrencyLevel"/> is less than 1.
268 /// </exception>
269 /// <exception cref="T:System.ArgumentException"><paramref name="collection"/> contains one or more duplicate keys.</exception>
270 public ConcurrentDictionary(
271 int concurrencyLevel, IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
272 : this(concurrencyLevel, DEFAULT_CAPACITY, false, comparer)
273 {
274 if (collection == null) throw new ArgumentNullException("collection");
275 if (comparer == null) throw new ArgumentNullException("comparer");
276
277 InitializeFromCollection(collection);
278 }
279
280 private void InitializeFromCollection(IEnumerable<KeyValuePair<TKey, TValue>> collection)
281 {
282 TValue dummy;
283 foreach (KeyValuePair<TKey, TValue> pair in collection)
284 {
285 if (pair.Key == null) throw new ArgumentNullException("key");
286
287 if (!TryAddInternal(pair.Key, pair.Value, false, false, out dummy))
288 {
289 throw new ArgumentException(GetResource("ConcurrentDictionary_SourceContainsDuplicateKeys"));
290 }
291 }
292
293 if (m_budget == 0)
294 {
295 m_budget = m_tables.m_buckets.Length / m_tables.m_locks.Length;
296 }
297
298 }
299
300 /// <summary>
301 /// Initializes a new instance of the <see cref="ConcurrentDictionary{TKey,TValue}"/>
302 /// class that is empty, has the specified concurrency level, has the specified initial capacity, and
303 /// uses the specified <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>.
304 /// </summary>
305 /// <param name="concurrencyLevel">The estimated number of threads that will update the
306 /// <see cref="ConcurrentDictionary{TKey,TValue}"/> concurrently.</param>
307 /// <param name="capacity">The initial number of elements that the <see
308 /// cref="ConcurrentDictionary{TKey,TValue}"/>
309 /// can contain.</param>
310 /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{TKey}"/>
311 /// implementation to use when comparing keys.</param>
312 /// <exception cref="T:System.ArgumentOutOfRangeException">
313 /// <paramref name="concurrencyLevel"/> is less than 1. -or-
314 /// <paramref name="capacity"/> is less than 0.
315 /// </exception>
316 /// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference
317 /// (Nothing in Visual Basic).</exception>
318 public ConcurrentDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
319 : this(concurrencyLevel, capacity, false, comparer)
320 {
321 }
322
323 internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer)
324 {
325 if (concurrencyLevel < 1)
326 {
327 throw new ArgumentOutOfRangeException("concurrencyLevel", GetResource("ConcurrentDictionary_ConcurrencyLevelMustBePositive"));
328 }
329 if (capacity < 0)
330 {
331 throw new ArgumentOutOfRangeException("capacity", GetResource("ConcurrentDictionary_CapacityMustNotBeNegative"));
332 }
333 if (comparer == null) throw new ArgumentNullException("comparer");
334
335 // The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
336 // any buckets.
337 if (capacity < concurrencyLevel)
338 {
339 capacity = concurrencyLevel;
340 }
341
342 object[] locks = new object[concurrencyLevel];
343 for (int i = 0; i < locks.Length; i++)
344 {
345 locks[i] = new object();
346 }
347
348 int[] countPerLock = new int[locks.Length];
349 Node[] buckets = new Node[capacity];
350 m_tables = new Tables(buckets, locks, countPerLock, comparer);
351
352 m_growLockArray = growLockArray;
353 m_budget = buckets.Length / locks.Length;
354 }
355
356
357 /// <summary>
358 /// Attempts to add the specified key and value to the <see cref="ConcurrentDictionary{TKey,
359 /// TValue}"/>.
360 /// </summary>
361 /// <param name="key">The key of the element to add.</param>
362 /// <param name="value">The value of the element to add. The value can be a null reference (Nothing
363 /// in Visual Basic) for reference types.</param>
364 /// <returns>true if the key/value pair was added to the <see cref="ConcurrentDictionary{TKey,
365 /// TValue}"/>
366 /// successfully; otherwise, false.</returns>
367 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null reference
368 /// (Nothing in Visual Basic).</exception>
369 /// <exception cref="T:System.OverflowException">The <see cref="ConcurrentDictionary{TKey, TValue}"/>
370 /// contains too many elements.</exception>
371 public bool TryAdd(TKey key, TValue value)
372 {
373 if (key == null) throw new ArgumentNullException("key");
374 TValue dummy;
375 return TryAddInternal(key, value, false, true, out dummy);
376 }
377
378 /// <summary>
379 /// Determines whether the <see cref="ConcurrentDictionary{TKey, TValue}"/> contains the specified
380 /// key.
381 /// </summary>
382 /// <param name="key">The key to locate in the <see cref="ConcurrentDictionary{TKey,
383 /// TValue}"/>.</param>
384 /// <returns>true if the <see cref="ConcurrentDictionary{TKey, TValue}"/> contains an element with
385 /// the specified key; otherwise, false.</returns>
386 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
387 /// (Nothing in Visual Basic).</exception>
388 public bool ContainsKey(TKey key)
389 {
390 if (key == null) throw new ArgumentNullException("key");
391
392 TValue throwAwayValue;
393 return TryGetValue(key, out throwAwayValue);
394 }
395
396 /// <summary>
397 /// Attempts to remove and return the the value with the specified key from the
398 /// <see cref="ConcurrentDictionary{TKey, TValue}"/>.
399 /// </summary>
400 /// <param name="key">The key of the element to remove and return.</param>
401 /// <param name="value">When this method returns, <paramref name="value"/> contains the object removed from the
402 /// <see cref="ConcurrentDictionary{TKey,TValue}"/> or the default value of <typeparamref
403 /// name="TValue"/>
404 /// if the operation failed.</param>
405 /// <returns>true if an object was removed successfully; otherwise, false.</returns>
406 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
407 /// (Nothing in Visual Basic).</exception>
408 public bool TryRemove(TKey key, out TValue value)
409 {
410 if (key == null) throw new ArgumentNullException("key");
411
412 return TryRemoveInternal(key, out value, false, default(TValue));
413 }
414
415 /// <summary>
416 /// Removes the specified key from the dictionary if it exists and returns its associated value.
417 /// If matchValue flag is set, the key will be removed only if is associated with a particular
418 /// value.
419 /// </summary>
420 /// <param name="key">The key to search for and remove if it exists.</param>
421 /// <param name="value">The variable into which the removed value, if found, is stored.</param>
422 /// <param name="matchValue">Whether removal of the key is conditional on its value.</param>
423 /// <param name="oldValue">The conditional value to compare against if <paramref name="matchValue"/> is true</param>
424 /// <returns></returns>
425 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
426 private bool TryRemoveInternal(TKey key, out TValue value, bool matchValue, TValue oldValue)
427 {
428 while (true)
429 {
430 Tables tables = m_tables;
431
432 IEqualityComparer<TKey> comparer = tables.m_comparer;
433
434 int bucketNo, lockNo;
435 GetBucketAndLockNo(comparer.GetHashCode(key), out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
436
437 lock (tables.m_locks[lockNo])
438 {
439 // If the table just got resized, we may not be holding the right lock, and must retry.
440 // This should be a rare occurence.
441 if (tables != m_tables)
442 {
443 continue;
444 }
445
446 Node prev = null;
447 for (Node curr = tables.m_buckets[bucketNo]; curr != null; curr = curr.m_next)
448 {
449 Assert((prev == null && curr == tables.m_buckets[bucketNo]) || prev.m_next == curr);
450
451 if (comparer.Equals(curr.m_key, key))
452 {
453 if (matchValue)
454 {
455 bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr.m_value);
456 if (!valuesMatch)
457 {
458 value = default(TValue);
459 return false;
460 }
461 }
462
463 if (prev == null)
464 {
465 Volatile.Write<Node>(ref tables.m_buckets[bucketNo], curr.m_next);
466 }
467 else
468 {
469 prev.m_next = curr.m_next;
470 }
471
472 value = curr.m_value;
473 tables.m_countPerLock[lockNo]--;
474 return true;
475 }
476 prev = curr;
477 }
478 }
479
480 value = default(TValue);
481 return false;
482 }
483 }
484
485 /// <summary>
486 /// Attempts to get the value associated with the specified key from the <see
487 /// cref="ConcurrentDictionary{TKey,TValue}"/>.
488 /// </summary>
489 /// <param name="key">The key of the value to get.</param>
490 /// <param name="value">When this method returns, <paramref name="value"/> contains the object from
491 /// the
492 /// <see cref="ConcurrentDictionary{TKey,TValue}"/> with the specified key or the default value of
493 /// <typeparamref name="TValue"/>, if the operation failed.</param>
494 /// <returns>true if the key was found in the <see cref="ConcurrentDictionary{TKey,TValue}"/>;
495 /// otherwise, false.</returns>
496 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
497 /// (Nothing in Visual Basic).</exception>
498 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
499 public bool TryGetValue(TKey key, out TValue value)
500 {
501 if (key == null) throw new ArgumentNullException("key");
502
503 int bucketNo, lockNoUnused;
504
505 // We must capture the m_buckets field in a local variable. It is set to a new table on each table resize.
506 Tables tables = m_tables;
507 IEqualityComparer<TKey> comparer = tables.m_comparer;
508 GetBucketAndLockNo(comparer.GetHashCode(key), out bucketNo, out lockNoUnused, tables.m_buckets.Length, tables.m_locks.Length);
509
510 // We can get away w/out a lock here.
511 // The Volatile.Read ensures that the load of the fields of 'n' doesn't move before the load from buckets[i].
512 Node n = Volatile.Read<Node>(ref tables.m_buckets[bucketNo]);
513
514 while (n != null)
515 {
516 if (comparer.Equals(n.m_key, key))
517 {
518 value = n.m_value;
519 return true;
520 }
521 n = n.m_next;
522 }
523
524 value = default(TValue);
525 return false;
526 }
527
528 /// <summary>
529 /// Compares the existing value for the specified key with a specified value, and if they're equal,
530 /// updates the key with a third value.
531 /// </summary>
532 /// <param name="key">The key whose value is compared with <paramref name="comparisonValue"/> and
533 /// possibly replaced.</param>
534 /// <param name="newValue">The value that replaces the value of the element with <paramref
535 /// name="key"/> if the comparison results in equality.</param>
536 /// <param name="comparisonValue">The value that is compared to the value of the element with
537 /// <paramref name="key"/>.</param>
538 /// <returns>true if the value with <paramref name="key"/> was equal to <paramref
539 /// name="comparisonValue"/> and replaced with <paramref name="newValue"/>; otherwise,
540 /// false.</returns>
541 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null
542 /// reference.</exception>
543 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
544 public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
545 {
546 if (key == null) throw new ArgumentNullException("key");
547
548 IEqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
549
550 while (true)
551 {
552 int bucketNo;
553 int lockNo;
554 int hashcode;
555
556 Tables tables = m_tables;
557 IEqualityComparer<TKey> comparer = tables.m_comparer;
558
559 hashcode = comparer.GetHashCode(key);
560 GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
561
562 lock (tables.m_locks[lockNo])
563 {
564 // If the table just got resized, we may not be holding the right lock, and must retry.
565 // This should be a rare occurence.
566 if (tables != m_tables)
567 {
568 continue;
569 }
570
571 // Try to find this key in the bucket
572 Node prev = null;
573 for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
574 {
575 Assert((prev == null && node == tables.m_buckets[bucketNo]) || prev.m_next == node);
576 if (comparer.Equals(node.m_key, key))
577 {
578 if (valueComparer.Equals(node.m_value, comparisonValue))
579 {
580 if (s_isValueWriteAtomic)
581 {
582 node.m_value = newValue;
583 }
584 else
585 {
586 Node newNode = new Node(node.m_key, newValue, hashcode, node.m_next);
587
588 if (prev == null)
589 {
590 tables.m_buckets[bucketNo] = newNode;
591 }
592 else
593 {
594 prev.m_next = newNode;
595 }
596 }
597
598 return true;
599 }
600
601 return false;
602 }
603
604 prev = node;
605 }
606
607 //didn't find the key
608 return false;
609 }
610 }
611 }
612
613 /// <summary>
614 /// Removes all keys and values from the <see cref="ConcurrentDictionary{TKey,TValue}"/>.
615 /// </summary>
616 public void Clear()
617 {
618 int locksAcquired = 0;
619 try
620 {
621 AcquireAllLocks(ref locksAcquired);
622
623 Tables newTables = new Tables(new Node[DEFAULT_CAPACITY], m_tables.m_locks, new int[m_tables.m_countPerLock.Length], m_tables.m_comparer);
624 m_tables = newTables;
625 m_budget = Math.Max(1, newTables.m_buckets.Length / newTables.m_locks.Length);
626 }
627 finally
628 {
629 ReleaseLocks(0, locksAcquired);
630 }
631 }
632
633 /// <summary>
634 /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection"/> to an array of
635 /// type <see cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>, starting at the
636 /// specified array index.
637 /// </summary>
638 /// <param name="array">The one-dimensional array of type <see
639 /// cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>
640 /// that is the destination of the <see
641 /// cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/> elements copied from the <see
642 /// cref="T:System.Collections.ICollection"/>. The array must have zero-based indexing.</param>
643 /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
644 /// begins.</param>
645 /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is a null reference
646 /// (Nothing in Visual Basic).</exception>
647 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is less than
648 /// 0.</exception>
649 /// <exception cref="T:System.ArgumentException"><paramref name="index"/> is equal to or greater than
650 /// the length of the <paramref name="array"/>. -or- The number of elements in the source <see
651 /// cref="T:System.Collections.ICollection"/>
652 /// is greater than the available space from <paramref name="index"/> to the end of the destination
653 /// <paramref name="array"/>.</exception>
654 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
655 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
656 {
657 if (array == null) throw new ArgumentNullException("array");
658 if (index < 0) throw new ArgumentOutOfRangeException("index", GetResource("ConcurrentDictionary_IndexIsNegative"));
659
660 int locksAcquired = 0;
661 try
662 {
663 AcquireAllLocks(ref locksAcquired);
664
665 int count = 0;
666
667 for (int i = 0; i < m_tables.m_locks.Length && count >= 0; i++)
668 {
669 count += m_tables.m_countPerLock[i];
670 }
671
672 if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
673 {
674 throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayNotLargeEnough"));
675 }
676
677 CopyToPairs(array, index);
678 }
679 finally
680 {
681 ReleaseLocks(0, locksAcquired);
682 }
683 }
684
685 /// <summary>
686 /// Copies the key and value pairs stored in the <see cref="ConcurrentDictionary{TKey,TValue}"/> to a
687 /// new array.
688 /// </summary>
689 /// <returns>A new array containing a snapshot of key and value pairs copied from the <see
690 /// cref="ConcurrentDictionary{TKey,TValue}"/>.</returns>
691 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
692 public KeyValuePair<TKey, TValue>[] ToArray()
693 {
694 int locksAcquired = 0;
695 try
696 {
697 AcquireAllLocks(ref locksAcquired);
698 int count = 0;
699 checked
700 {
701 for (int i = 0; i < m_tables.m_locks.Length; i++)
702 {
703 count += m_tables.m_countPerLock[i];
704 }
705 }
706
707 KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];
708
709 CopyToPairs(array, 0);
710 return array;
711 }
712 finally
713 {
714 ReleaseLocks(0, locksAcquired);
715 }
716 }
717
718 /// <summary>
719 /// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
720 ///
721 /// Important: the caller must hold all locks in m_locks before calling CopyToPairs.
722 /// </summary>
723 private void CopyToPairs(KeyValuePair<TKey, TValue>[] array, int index)
724 {
725 Node[] buckets = m_tables.m_buckets;
726 for (int i = 0; i < buckets.Length; i++)
727 {
728 for (Node current = buckets[i]; current != null; current = current.m_next)
729 {
730 array[index] = new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
731 index++; //this should never flow, CopyToPairs is only called when there's no overflow risk
732 }
733 }
734 }
735
736 /// <summary>
737 /// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
738 ///
739 /// Important: the caller must hold all locks in m_locks before calling CopyToEntries.
740 /// </summary>
741 private void CopyToEntries(DictionaryEntry[] array, int index)
742 {
743 Node[] buckets = m_tables.m_buckets;
744 for (int i = 0; i < buckets.Length; i++)
745 {
746 for (Node current = buckets[i]; current != null; current = current.m_next)
747 {
748 array[index] = new DictionaryEntry(current.m_key, current.m_value);
749 index++; //this should never flow, CopyToEntries is only called when there's no overflow risk
750 }
751 }
752 }
753
754 /// <summary>
755 /// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
756 ///
757 /// Important: the caller must hold all locks in m_locks before calling CopyToObjects.
758 /// </summary>
759 private void CopyToObjects(object[] array, int index)
760 {
761 Node[] buckets = m_tables.m_buckets;
762 for (int i = 0; i < buckets.Length; i++)
763 {
764 for (Node current = buckets[i]; current != null; current = current.m_next)
765 {
766 array[index] = new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
767 index++; //this should never flow, CopyToObjects is only called when there's no overflow risk
768 }
769 }
770 }
771
772 /// <summary>Returns an enumerator that iterates through the <see
773 /// cref="ConcurrentDictionary{TKey,TValue}"/>.</summary>
774 /// <returns>An enumerator for the <see cref="ConcurrentDictionary{TKey,TValue}"/>.</returns>
775 /// <remarks>
776 /// The enumerator returned from the dictionary is safe to use concurrently with
777 /// reads and writes to the dictionary, however it does not represent a moment-in-time snapshot
778 /// of the dictionary. The contents exposed through the enumerator may contain modifications
779 /// made to the dictionary after <see cref="GetEnumerator"/> was called.
780 /// </remarks>
781 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
782 {
783 Node[] buckets = m_tables.m_buckets;
784
785 for (int i = 0; i < buckets.Length; i++)
786 {
787 // The Volatile.Read ensures that the load of the fields of 'current' doesn't move before the load from buckets[i].
788 Node current = Volatile.Read<Node>(ref buckets[i]);
789
790 while (current != null)
791 {
792 yield return new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
793 current = current.m_next;
794 }
795 }
796 }
797
798 /// <summary>
799 /// Shared internal implementation for inserts and updates.
800 /// If key exists, we always return false; and if updateIfExists == true we force update with value;
801 /// If key doesn't exist, we always add value and return true;
802 /// </summary>
803 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
804 private bool TryAddInternal(TKey key, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
805 {
806 while (true)
807 {
808 int bucketNo, lockNo;
809 int hashcode;
810
811 Tables tables = m_tables;
812 IEqualityComparer<TKey> comparer = tables.m_comparer;
813 hashcode = comparer.GetHashCode(key);
814 GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
815
816 bool resizeDesired = false;
817 bool lockTaken = false;
818 #if FEATURE_RANDOMIZED_STRING_HASHING
819 #if !FEATURE_CORECLR
820 bool resizeDueToCollisions = false;
821 #endif // !FEATURE_CORECLR
822 #endif
823
824 try
825 {
826 if (acquireLock)
827 Monitor.Enter(tables.m_locks[lockNo], ref lockTaken);
828
829 // If the table just got resized, we may not be holding the right lock, and must retry.
830 // This should be a rare occurence.
831 if (tables != m_tables)
832 {
833 continue;
834 }
835
836 #if FEATURE_RANDOMIZED_STRING_HASHING
837 #if !FEATURE_CORECLR
838 int collisionCount = 0;
839 #endif // !FEATURE_CORECLR
840 #endif
841
842 // Try to find this key in the bucket
843 Node prev = null;
844 for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
845 {
846 Assert((prev == null && node == tables.m_buckets[bucketNo]) || prev.m_next == node);
847 if (comparer.Equals(node.m_key, key))
848 {
849 // The key was found in the dictionary. If updates are allowed, update the value for that key.
850 // We need to create a new node for the update, in order to support TValue types that cannot
851 // be written atomically, since lock-free reads may be happening concurrently.
852 if (updateIfExists)
853 {
854 if (s_isValueWriteAtomic)
855 {
856 node.m_value = value;
857 }
858 else
859 {
860 Node newNode = new Node(node.m_key, value, hashcode, node.m_next);
861 if (prev == null)
862 {
863 tables.m_buckets[bucketNo] = newNode;
864 }
865 else
866 {
867 prev.m_next = newNode;
868 }
869 }
870 resultingValue = value;
871 }
872 else
873 {
874 resultingValue = node.m_value;
875 }
876 return false;
877 }
878 prev = node;
879
880 #if FEATURE_RANDOMIZED_STRING_HASHING
881 #if !FEATURE_CORECLR
882 collisionCount++;
883 #endif // !FEATURE_CORECLR
884 #endif
885 }
886
887 #if FEATURE_RANDOMIZED_STRING_HASHING
888 #if !FEATURE_CORECLR
889 if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
890 {
891 resizeDesired = true;
892 resizeDueToCollisions = true;
893 }
894 #endif // !FEATURE_CORECLR
895 #endif
896
897 // The key was not found in the bucket. Insert the key-value pair.
898 Volatile.Write<Node>(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo]));
899 checked
900 {
901 tables.m_countPerLock[lockNo]++;
902 }
903
904 //
905 // If the number of elements guarded by this lock has exceeded the budget, resize the bucket table.
906 // It is also possible that GrowTable will increase the budget but won't resize the bucket table.
907 // That happens if the bucket table is found to be poorly utilized due to a bad hash function.
908 //
909 if (tables.m_countPerLock[lockNo] > m_budget)
910 {
911 resizeDesired = true;
912 }
913 }
914 finally
915 {
916 if (lockTaken)
917 Monitor.Exit(tables.m_locks[lockNo]);
918 }
919
920 //
921 // The fact that we got here means that we just performed an insertion. If necessary, we will grow the table.
922 //
923 // Concurrency notes:
924 // - Notice that we are not holding any locks at when calling GrowTable. This is necessary to prevent deadlocks.
925 // - As a result, it is possible that GrowTable will be called unnecessarily. But, GrowTable will obtain lock 0
926 // and then verify that the table we passed to it as the argument is still the current table.
927 //
928 if (resizeDesired)
929 {
930 #if FEATURE_RANDOMIZED_STRING_HASHING
931 #if !FEATURE_CORECLR
932 if (resizeDueToCollisions)
933 {
934 GrowTable(tables, (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer), true, m_keyRehashCount);
935 }
936 else
937 #endif // !FEATURE_CORECLR
938 {
939 GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
940 }
941 #else
942 GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
943 #endif
944 }
945
946 resultingValue = value;
947 return true;
948 }
949 }
950
951 /// <summary>
952 /// Gets or sets the value associated with the specified key.
953 /// </summary>
954 /// <param name="key">The key of the value to get or set.</param>
955 /// <value>The value associated with the specified key. If the specified key is not found, a get
956 /// operation throws a
957 /// <see cref="T:Sytem.Collections.Generic.KeyNotFoundException"/>, and a set operation creates a new
958 /// element with the specified key.</value>
959 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
960 /// (Nothing in Visual Basic).</exception>
961 /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and
962 /// <paramref name="key"/>
963 /// does not exist in the collection.</exception>
964 public TValue this[TKey key]
965 {
966 get
967 {
968 TValue value;
969 if (!TryGetValue(key, out value))
970 {
971 throw new KeyNotFoundException();
972 }
973 return value;
974 }
975 set
976 {
977 if (key == null) throw new ArgumentNullException("key");
978 TValue dummy;
979 TryAddInternal(key, value, true, true, out dummy);
980 }
981 }
982
983 /// <summary>
984 /// Gets the number of key/value pairs contained in the <see
985 /// cref="ConcurrentDictionary{TKey,TValue}"/>.
986 /// </summary>
987 /// <exception cref="T:System.OverflowException">The dictionary contains too many
988 /// elements.</exception>
989 /// <value>The number of key/value paris contained in the <see
990 /// cref="ConcurrentDictionary{TKey,TValue}"/>.</value>
991 /// <remarks>Count has snapshot semantics and represents the number of items in the <see
992 /// cref="ConcurrentDictionary{TKey,TValue}"/>
993 /// at the moment when Count was accessed.</remarks>
994 public int Count
995 {
996 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
997 get
998 {
999 int count = 0;
1000
1001 int acquiredLocks = 0;
1002 try
1003 {
1004 // Acquire all locks
1005 AcquireAllLocks(ref acquiredLocks);
1006
1007 // Compute the count, we allow overflow
1008 for (int i = 0; i < m_tables.m_countPerLock.Length; i++)
1009 {
1010 count += m_tables.m_countPerLock[i];
1011 }
1012
1013 }
1014 finally
1015 {
1016 // Release locks that have been acquired earlier
1017 ReleaseLocks(0, acquiredLocks);
1018 }
1019
1020 return count;
1021 }
1022 }
1023
1024 /// <summary>
1025 /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
1026 /// if the key does not already exist.
1027 /// </summary>
1028 /// <param name="key">The key of the element to add.</param>
1029 /// <param name="valueFactory">The function used to generate a value for the key</param>
1030 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1031 /// (Nothing in Visual Basic).</exception>
1032 /// <exception cref="T:System.ArgumentNullException"><paramref name="valueFactory"/> is a null reference
1033 /// (Nothing in Visual Basic).</exception>
1034 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1035 /// elements.</exception>
1036 /// <returns>The value for the key. This will be either the existing value for the key if the
1037 /// key is already in the dictionary, or the new value for the key as returned by valueFactory
1038 /// if the key was not in the dictionary.</returns>
1039 public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
1040 {
1041 if (key == null) throw new ArgumentNullException("key");
1042 if (valueFactory == null) throw new ArgumentNullException("valueFactory");
1043
1044 TValue resultingValue;
1045 if (TryGetValue(key, out resultingValue))
1046 {
1047 return resultingValue;
1048 }
1049 TryAddInternal(key, valueFactory(key), false, true, out resultingValue);
1050 return resultingValue;
1051 }
1052
1053 /// <summary>
1054 /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/>
1055 /// if the key does not already exist.
1056 /// </summary>
1057 /// <param name="key">The key of the element to add.</param>
1058 /// <param name="value">the value to be added, if the key does not already exist</param>
1059 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1060 /// (Nothing in Visual Basic).</exception>
1061 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1062 /// elements.</exception>
1063 /// <returns>The value for the key. This will be either the existing value for the key if the
1064 /// key is already in the dictionary, or the new value if the key was not in the dictionary.</returns>
1065 public TValue GetOrAdd(TKey key, TValue value)
1066 {
1067 if (key == null) throw new ArgumentNullException("key");
1068
1069 TValue resultingValue;
1070 TryAddInternal(key, value, false, true, out resultingValue);
1071 return resultingValue;
1072 }
1073
1074 /// <summary>
1075 /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key does not already
1076 /// exist, or updates a key/value pair in the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key
1077 /// already exists.
1078 /// </summary>
1079 /// <param name="key">The key to be added or whose value should be updated</param>
1080 /// <param name="addValueFactory">The function used to generate a value for an absent key</param>
1081 /// <param name="updateValueFactory">The function used to generate a new value for an existing key
1082 /// based on the key's existing value</param>
1083 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1084 /// (Nothing in Visual Basic).</exception>
1085 /// <exception cref="T:System.ArgumentNullException"><paramref name="addValueFactory"/> is a null reference
1086 /// (Nothing in Visual Basic).</exception>
1087 /// <exception cref="T:System.ArgumentNullException"><paramref name="updateValueFactory"/> is a null reference
1088 /// (Nothing in Visual Basic).</exception>
1089 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1090 /// elements.</exception>
1091 /// <returns>The new value for the key. This will be either be the result of addValueFactory (if the key was
1092 /// absent) or the result of updateValueFactory (if the key was present).</returns>
1093 public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
1094 {
1095 if (key == null) throw new ArgumentNullException("key");
1096 if (addValueFactory == null) throw new ArgumentNullException("addValueFactory");
1097 if (updateValueFactory == null) throw new ArgumentNullException("updateValueFactory");
1098
1099 TValue newValue, resultingValue;
1100 while (true)
1101 {
1102 TValue oldValue;
1103 if (TryGetValue(key, out oldValue))
1104 //key exists, try to update
1105 {
1106 newValue = updateValueFactory(key, oldValue);
1107 if (TryUpdate(key, newValue, oldValue))
1108 {
1109 return newValue;
1110 }
1111 }
1112 else //try add
1113 {
1114 newValue = addValueFactory(key);
1115 if (TryAddInternal(key, newValue, false, true, out resultingValue))
1116 {
1117 return resultingValue;
1118 }
1119 }
1120 }
1121 }
1122
1123 /// <summary>
1124 /// Adds a key/value pair to the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key does not already
1125 /// exist, or updates a key/value pair in the <see cref="ConcurrentDictionary{TKey,TValue}"/> if the key
1126 /// already exists.
1127 /// </summary>
1128 /// <param name="key">The key to be added or whose value should be updated</param>
1129 /// <param name="addValue">The value to be added for an absent key</param>
1130 /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on
1131 /// the key's existing value</param>
1132 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1133 /// (Nothing in Visual Basic).</exception>
1134 /// <exception cref="T:System.ArgumentNullException"><paramref name="updateValueFactory"/> is a null reference
1135 /// (Nothing in Visual Basic).</exception>
1136 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1137 /// elements.</exception>
1138 /// <returns>The new value for the key. This will be either be the result of addValueFactory (if the key was
1139 /// absent) or the result of updateValueFactory (if the key was present).</returns>
1140 public TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
1141 {
1142 if (key == null) throw new ArgumentNullException("key");
1143 if (updateValueFactory == null) throw new ArgumentNullException("updateValueFactory");
1144 TValue newValue, resultingValue;
1145 while (true)
1146 {
1147 TValue oldValue;
1148 if (TryGetValue(key, out oldValue))
1149 //key exists, try to update
1150 {
1151 newValue = updateValueFactory(key, oldValue);
1152 if (TryUpdate(key, newValue, oldValue))
1153 {
1154 return newValue;
1155 }
1156 }
1157 else //try add
1158 {
1159 if (TryAddInternal(key, addValue, false, true, out resultingValue))
1160 {
1161 return resultingValue;
1162 }
1163 }
1164 }
1165 }
1166
1167
1168
1169 /// <summary>
1170 /// Gets a value that indicates whether the <see cref="ConcurrentDictionary{TKey,TValue}"/> is empty.
1171 /// </summary>
1172 /// <value>true if the <see cref="ConcurrentDictionary{TKey,TValue}"/> is empty; otherwise,
1173 /// false.</value>
1174 public bool IsEmpty
1175 {
1176 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
1177 get
1178 {
1179 int acquiredLocks = 0;
1180 try
1181 {
1182 // Acquire all locks
1183 AcquireAllLocks(ref acquiredLocks);
1184
1185 for (int i = 0; i < m_tables.m_countPerLock.Length; i++)
1186 {
1187 if (m_tables.m_countPerLock[i] != 0)
1188 {
1189 return false;
1190 }
1191 }
1192 }
1193 finally
1194 {
1195 // Release locks that have been acquired earlier
1196 ReleaseLocks(0, acquiredLocks);
1197 }
1198
1199 return true;
1200 }
1201 }
1202
1203 #region IDictionary<TKey,TValue> members
1204
1205 /// <summary>
1206 /// Adds the specified key and value to the <see
1207 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.
1208 /// </summary>
1209 /// <param name="key">The object to use as the key of the element to add.</param>
1210 /// <param name="value">The object to use as the value of the element to add.</param>
1211 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1212 /// (Nothing in Visual Basic).</exception>
1213 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1214 /// elements.</exception>
1215 /// <exception cref="T:System.ArgumentException">
1216 /// An element with the same key already exists in the <see
1217 /// cref="ConcurrentDictionary{TKey,TValue}"/>.</exception>
1218 void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
1219 {
1220 if (!TryAdd(key, value))
1221 {
1222 throw new ArgumentException(GetResource("ConcurrentDictionary_KeyAlreadyExisted"));
1223 }
1224 }
1225
1226 /// <summary>
1227 /// Removes the element with the specified key from the <see
1228 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.
1229 /// </summary>
1230 /// <param name="key">The key of the element to remove.</param>
1231 /// <returns>true if the element is successfully remove; otherwise false. This method also returns
1232 /// false if
1233 /// <paramref name="key"/> was not found in the original <see
1234 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.
1235 /// </returns>
1236 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1237 /// (Nothing in Visual Basic).</exception>
1238 bool IDictionary<TKey, TValue>.Remove(TKey key)
1239 {
1240 TValue throwAwayValue;
1241 return TryRemove(key, out throwAwayValue);
1242 }
1243
1244 /// <summary>
1245 /// Gets a collection containing the keys in the <see
1246 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.
1247 /// </summary>
1248 /// <value>An <see cref="T:System.Collections.Generic.ICollection{TKey}"/> containing the keys in the
1249 /// <see cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.</value>
1250 public ICollection<TKey> Keys
1251 {
1252 get { return GetKeys(); }
1253 }
1254
1255 /// <summary>
1256 /// Gets an <see cref="T:System.Collections.Generic.IEnumerable{TKey}"/> containing the keys of
1257 /// the <see cref="T:System.Collections.Generic.IReadOnlyDictionary{TKey,TValue}"/>.
1258 /// </summary>
1259 /// <value>An <see cref="T:System.Collections.Generic.IEnumerable{TKey}"/> containing the keys of
1260 /// the <see cref="T:System.Collections.Generic.IReadOnlyDictionary{TKey,TValue}"/>.</value>
1261 IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
1262 {
1263 get { return GetKeys(); }
1264 }
1265
1266 /// <summary>
1267 /// Gets a collection containing the values in the <see
1268 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.
1269 /// </summary>
1270 /// <value>An <see cref="T:System.Collections.Generic.ICollection{TValue}"/> containing the values in
1271 /// the
1272 /// <see cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.</value>
1273 public ICollection<TValue> Values
1274 {
1275 get { return GetValues(); }
1276 }
1277
1278 /// <summary>
1279 /// Gets an <see cref="T:System.Collections.Generic.IEnumerable{TValue}"/> containing the values
1280 /// in the <see cref="T:System.Collections.Generic.IReadOnlyDictionary{TKey,TValue}"/>.
1281 /// </summary>
1282 /// <value>An <see cref="T:System.Collections.Generic.IEnumerable{TValue}"/> containing the
1283 /// values in the <see cref="T:System.Collections.Generic.IReadOnlyDictionary{TKey,TValue}"/>.</value>
1284 IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
1285 {
1286 get { return GetValues(); }
1287 }
1288 #endregion
1289
1290 #region ICollection<KeyValuePair<TKey,TValue>> Members
1291
1292 /// <summary>
1293 /// Adds the specified value to the <see cref="T:System.Collections.Generic.ICollection{TValue}"/>
1294 /// with the specified key.
1295 /// </summary>
1296 /// <param name="keyValuePair">The <see cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>
1297 /// structure representing the key and value to add to the <see
1298 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.</param>
1299 /// <exception cref="T:System.ArgumentNullException">The <paramref name="keyValuePair"/> of <paramref
1300 /// name="keyValuePair"/> is null.</exception>
1301 /// <exception cref="T:System.OverflowException">The <see
1302 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>
1303 /// contains too many elements.</exception>
1304 /// <exception cref="T:System.ArgumentException">An element with the same key already exists in the
1305 /// <see cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/></exception>
1306 void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
1307 {
1308 ((IDictionary<TKey, TValue>)this).Add(keyValuePair.Key, keyValuePair.Value);
1309 }
1310
1311 /// <summary>
1312 /// Determines whether the <see cref="T:System.Collections.Generic.ICollection{TKey,TValue}"/>
1313 /// contains a specific key and value.
1314 /// </summary>
1315 /// <param name="keyValuePair">The <see cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>
1316 /// structure to locate in the <see
1317 /// cref="T:System.Collections.Generic.ICollection{TValue}"/>.</param>
1318 /// <returns>true if the <paramref name="keyValuePair"/> is found in the <see
1319 /// cref="T:System.Collections.Generic.ICollection{TKey,TValue}"/>; otherwise, false.</returns>
1320 bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
1321 {
1322 TValue value;
1323 if (!TryGetValue(keyValuePair.Key, out value))
1324 {
1325 return false;
1326 }
1327 return EqualityComparer<TValue>.Default.Equals(value, keyValuePair.Value);
1328 }
1329
1330 /// <summary>
1331 /// Gets a value indicating whether the dictionary is read-only.
1332 /// </summary>
1333 /// <value>true if the <see cref="T:System.Collections.Generic.ICollection{TKey,TValue}"/> is
1334 /// read-only; otherwise, false. For <see
1335 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>, this property always returns
1336 /// false.</value>
1337 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
1338 {
1339 get { return false; }
1340 }
1341
1342 /// <summary>
1343 /// Removes a key and value from the dictionary.
1344 /// </summary>
1345 /// <param name="keyValuePair">The <see
1346 /// cref="T:System.Collections.Generic.KeyValuePair{TKey,TValue}"/>
1347 /// structure representing the key and value to remove from the <see
1348 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.</param>
1349 /// <returns>true if the key and value represented by <paramref name="keyValuePair"/> is successfully
1350 /// found and removed; otherwise, false.</returns>
1351 /// <exception cref="T:System.ArgumentNullException">The Key property of <paramref
1352 /// name="keyValuePair"/> is a null reference (Nothing in Visual Basic).</exception>
1353 bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
1354 {
1355 if (keyValuePair.Key == null) throw new ArgumentNullException(GetResource("ConcurrentDictionary_ItemKeyIsNull"));
1356
1357 TValue throwAwayValue;
1358 return TryRemoveInternal(keyValuePair.Key, out throwAwayValue, true, keyValuePair.Value);
1359 }
1360
1361 #endregion
1362
1363 #region IEnumerable Members
1364
1365 /// <summary>Returns an enumerator that iterates through the <see
1366 /// cref="ConcurrentDictionary{TKey,TValue}"/>.</summary>
1367 /// <returns>An enumerator for the <see cref="ConcurrentDictionary{TKey,TValue}"/>.</returns>
1368 /// <remarks>
1369 /// The enumerator returned from the dictionary is safe to use concurrently with
1370 /// reads and writes to the dictionary, however it does not represent a moment-in-time snapshot
1371 /// of the dictionary. The contents exposed through the enumerator may contain modifications
1372 /// made to the dictionary after <see cref="GetEnumerator"/> was called.
1373 /// </remarks>
1374 IEnumerator IEnumerable.GetEnumerator()
1375 {
1376 return ((ConcurrentDictionary<TKey, TValue>)this).GetEnumerator();
1377 }
1378
1379 #endregion
1380
1381 #region IDictionary Members
1382
1383 /// <summary>
1384 /// Adds the specified key and value to the dictionary.
1385 /// </summary>
1386 /// <param name="key">The object to use as the key.</param>
1387 /// <param name="value">The object to use as the value.</param>
1388 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1389 /// (Nothing in Visual Basic).</exception>
1390 /// <exception cref="T:System.OverflowException">The dictionary contains too many
1391 /// elements.</exception>
1392 /// <exception cref="T:System.ArgumentException">
1393 /// <paramref name="key"/> is of a type that is not assignable to the key type <typeparamref
1394 /// name="TKey"/> of the <see cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>. -or-
1395 /// <paramref name="value"/> is of a type that is not assignable to <typeparamref name="TValue"/>,
1396 /// the type of values in the <see cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.
1397 /// -or- A value with the same key already exists in the <see
1398 /// cref="T:System.Collections.Generic.Dictionary{TKey,TValue}"/>.
1399 /// </exception>
1400 void IDictionary.Add(object key, object value)
1401 {
1402 if (key == null) throw new ArgumentNullException("key");
1403 if (!(key is TKey)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfKeyIncorrect"));
1404
1405 TValue typedValue;
1406 try
1407 {
1408 typedValue = (TValue)value;
1409 }
1410 catch (InvalidCastException)
1411 {
1412 throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfValueIncorrect"));
1413 }
1414
1415 ((IDictionary<TKey, TValue>)this).Add((TKey)key, typedValue);
1416 }
1417
1418 /// <summary>
1419 /// Gets whether the <see cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> contains an
1420 /// element with the specified key.
1421 /// </summary>
1422 /// <param name="key">The key to locate in the <see
1423 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.</param>
1424 /// <returns>true if the <see cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> contains
1425 /// an element with the specified key; otherwise, false.</returns>
1426 /// <exception cref="T:System.ArgumentNullException"> <paramref name="key"/> is a null reference
1427 /// (Nothing in Visual Basic).</exception>
1428 bool IDictionary.Contains(object key)
1429 {
1430 if (key == null) throw new ArgumentNullException("key");
1431
1432 return (key is TKey) && ((ConcurrentDictionary<TKey, TValue>)this).ContainsKey((TKey)key);
1433 }
1434
1435 /// <summary>Provides an <see cref="T:System.Collections.Generics.IDictionaryEnumerator"/> for the
1436 /// <see cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.</summary>
1437 /// <returns>An <see cref="T:System.Collections.Generics.IDictionaryEnumerator"/> for the <see
1438 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.</returns>
1439 IDictionaryEnumerator IDictionary.GetEnumerator()
1440 {
1441 return new DictionaryEnumerator(this);
1442 }
1443
1444 /// <summary>
1445 /// Gets a value indicating whether the <see
1446 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> has a fixed size.
1447 /// </summary>
1448 /// <value>true if the <see cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> has a
1449 /// fixed size; otherwise, false. For <see
1450 /// cref="T:System.Collections.Generic.ConcurrentDictionary{TKey,TValue}"/>, this property always
1451 /// returns false.</value>
1452 bool IDictionary.IsFixedSize
1453 {
1454 get { return false; }
1455 }
1456
1457 /// <summary>
1458 /// Gets a value indicating whether the <see
1459 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> is read-only.
1460 /// </summary>
1461 /// <value>true if the <see cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/> is
1462 /// read-only; otherwise, false. For <see
1463 /// cref="T:System.Collections.Generic.ConcurrentDictionary{TKey,TValue}"/>, this property always
1464 /// returns false.</value>
1465 bool IDictionary.IsReadOnly
1466 {
1467 get { return false; }
1468 }
1469
1470 /// <summary>
1471 /// Gets an <see cref="T:System.Collections.ICollection"/> containing the keys of the <see
1472 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.
1473 /// </summary>
1474 /// <value>An <see cref="T:System.Collections.ICollection"/> containing the keys of the <see
1475 /// cref="T:System.Collections.Generic.IDictionary{TKey,TValue}"/>.</value>
1476 ICollection IDictionary.Keys
1477 {
1478 get { return GetKeys(); }
1479 }
1480
1481 /// <summary>
1482 /// Removes the element with the specified key from the <see
1483 /// cref="T:System.Collections.IDictionary"/>.
1484 /// </summary>
1485 /// <param name="key">The key of the element to remove.</param>
1486 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1487 /// (Nothing in Visual Basic).</exception>
1488 void IDictionary.Remove(object key)
1489 {
1490 if (key == null) throw new ArgumentNullException("key");
1491
1492 TValue throwAwayValue;
1493 if (key is TKey)
1494 {
1495 this.TryRemove((TKey)key, out throwAwayValue);
1496 }
1497 }
1498
1499 /// <summary>
1500 /// Gets an <see cref="T:System.Collections.ICollection"/> containing the values in the <see
1501 /// cref="T:System.Collections.IDictionary"/>.
1502 /// </summary>
1503 /// <value>An <see cref="T:System.Collections.ICollection"/> containing the values in the <see
1504 /// cref="T:System.Collections.IDictionary"/>.</value>
1505 ICollection IDictionary.Values
1506 {
1507 get { return GetValues(); }
1508 }
1509
1510 /// <summary>
1511 /// Gets or sets the value associated with the specified key.
1512 /// </summary>
1513 /// <param name="key">The key of the value to get or set.</param>
1514 /// <value>The value associated with the specified key, or a null reference (Nothing in Visual Basic)
1515 /// if <paramref name="key"/> is not in the dictionary or <paramref name="key"/> is of a type that is
1516 /// not assignable to the key type <typeparamref name="TKey"/> of the <see
1517 /// cref="T:System.Collections.Generic.ConcurrentDictionary{TKey,TValue}"/>.</value>
1518 /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
1519 /// (Nothing in Visual Basic).</exception>
1520 /// <exception cref="T:System.ArgumentException">
1521 /// A value is being assigned, and <paramref name="key"/> is of a type that is not assignable to the
1522 /// key type <typeparamref name="TKey"/> of the <see
1523 /// cref="T:System.Collections.Generic.ConcurrentDictionary{TKey,TValue}"/>. -or- A value is being
1524 /// assigned, and <paramref name="key"/> is of a type that is not assignable to the value type
1525 /// <typeparamref name="TValue"/> of the <see
1526 /// cref="T:System.Collections.Generic.ConcurrentDictionary{TKey,TValue}"/>
1527 /// </exception>
1528 object IDictionary.this[object key]
1529 {
1530 get
1531 {
1532 if (key == null) throw new ArgumentNullException("key");
1533
1534 TValue value;
1535 if (key is TKey && this.TryGetValue((TKey)key, out value))
1536 {
1537 return value;
1538 }
1539
1540 return null;
1541 }
1542 set
1543 {
1544 if (key == null) throw new ArgumentNullException("key");
1545
1546 if (!(key is TKey)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfKeyIncorrect"));
1547 if (!(value is TValue)) throw new ArgumentException(GetResource("ConcurrentDictionary_TypeOfValueIncorrect"));
1548
1549 ((ConcurrentDictionary<TKey, TValue>)this)[(TKey)key] = (TValue)value;
1550 }
1551 }
1552
1553 #endregion
1554
1555 #region ICollection Members
1556
1557 /// <summary>
1558 /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an array, starting
1559 /// at the specified array index.
1560 /// </summary>
1561 /// <param name="array">The one-dimensional array that is the destination of the elements copied from
1562 /// the <see cref="T:System.Collections.ICollection"/>. The array must have zero-based
1563 /// indexing.</param>
1564 /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
1565 /// begins.</param>
1566 /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is a null reference
1567 /// (Nothing in Visual Basic).</exception>
1568 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is less than
1569 /// 0.</exception>
1570 /// <exception cref="T:System.ArgumentException"><paramref name="index"/> is equal to or greater than
1571 /// the length of the <paramref name="array"/>. -or- The number of elements in the source <see
1572 /// cref="T:System.Collections.ICollection"/>
1573 /// is greater than the available space from <paramref name="index"/> to the end of the destination
1574 /// <paramref name="array"/>.</exception>
1575 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
1576 void ICollection.CopyTo(Array array, int index)
1577 {
1578 if (array == null) throw new ArgumentNullException("array");
1579 if (index < 0) throw new ArgumentOutOfRangeException("index", GetResource("ConcurrentDictionary_IndexIsNegative"));
1580
1581 int locksAcquired = 0;
1582 try
1583 {
1584 AcquireAllLocks(ref locksAcquired);
1585 Tables tables = m_tables;
1586
1587 int count = 0;
1588
1589 for (int i = 0; i < tables.m_locks.Length && count >= 0; i++)
1590 {
1591 count += tables.m_countPerLock[i];
1592 }
1593
1594 if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
1595 {
1596 throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayNotLargeEnough"));
1597 }
1598
1599 // To be consistent with the behavior of ICollection.CopyTo() in Dictionary<TKey,TValue>,
1600 // we recognize three types of target arrays:
1601 // - an array of KeyValuePair<TKey, TValue> structs
1602 // - an array of DictionaryEntry structs
1603 // - an array of objects
1604
1605 KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
1606 if (pairs != null)
1607 {
1608 CopyToPairs(pairs, index);
1609 return;
1610 }
1611
1612 DictionaryEntry[] entries = array as DictionaryEntry[];
1613 if (entries != null)
1614 {
1615 CopyToEntries(entries, index);
1616 return;
1617 }
1618
1619 object[] objects = array as object[];
1620 if (objects != null)
1621 {
1622 CopyToObjects(objects, index);
1623 return;
1624 }
1625
1626 throw new ArgumentException(GetResource("ConcurrentDictionary_ArrayIncorrectType"), "array");
1627 }
1628 finally
1629 {
1630 ReleaseLocks(0, locksAcquired);
1631 }
1632 }
1633
1634 /// <summary>
1635 /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
1636 /// synchronized with the SyncRoot.
1637 /// </summary>
1638 /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
1639 /// (thread safe); otherwise, false. For <see
1640 /// cref="T:System.Collections.Concurrent.ConcurrentDictionary{TKey,TValue}"/>, this property always
1641 /// returns false.</value>
1642 bool ICollection.IsSynchronized
1643 {
1644 get { return false; }
1645 }
1646
1647 /// <summary>
1648 /// Gets an object that can be used to synchronize access to the <see
1649 /// cref="T:System.Collections.ICollection"/>. This property is not supported.
1650 /// </summary>
1651 /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
1652 object ICollection.SyncRoot
1653 {
1654 get
1655 {
1656 throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
1657 }
1658 }
1659
1660 #endregion
1661
1662 /// <summary>
1663 /// Replaces the bucket table with a larger one. To prevent multiple threads from resizing the
1664 /// table as a result of ----s, the Tables instance that holds the table of buckets deemed too
1665 /// small is passed in as an argument to GrowTable(). GrowTable() obtains a lock, and then checks
1666 /// the Tables instance has been replaced in the meantime or not.
1667 /// The <paramref name="rehashCount"/> will be used to ensure that we don't do two subsequent resizes
1668 /// because of a collision
1669 /// </summary>
1670 private void GrowTable(Tables tables, IEqualityComparer<TKey> newComparer, bool regenerateHashKeys, int rehashCount)
1671 {
1672 int locksAcquired = 0;
1673 try
1674 {
1675 // The thread that first obtains m_locks[0] will be the one doing the resize operation
1676 AcquireLocks(0, 1, ref locksAcquired);
1677
1678 if (regenerateHashKeys && rehashCount == m_keyRehashCount)
1679 {
1680 // This method is called with regenerateHashKeys==true when we detected
1681 // more than HashHelpers.HashCollisionThreshold collisions when adding a new element.
1682 // In that case we are in the process of switching to another (randomized) comparer
1683 // and we have to re-hash all the keys in the table.
1684 // We are only going to do this if we did not just rehash the entire table while waiting for the lock
1685 tables = m_tables;
1686 }
1687 else
1688 {
1689 // If we don't require a regeneration of hash keys we want to make sure we don't do work when
1690 // we don't have to
1691 if (tables != m_tables)
1692 {
1693 // We assume that since the table reference is different, it was already resized (or the budget
1694 // was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
1695 // we will have to revisit this logic.
1696 return;
1697 }
1698
1699 // Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
1700 long approxCount = 0;
1701 for (int i = 0; i < tables.m_countPerLock.Length; i++)
1702 {
1703 approxCount += tables.m_countPerLock[i];
1704 }
1705
1706 //
1707 // If the bucket array is too empty, double the budget instead of resizing the table
1708 //
1709 if (approxCount < tables.m_buckets.Length / 4)
1710 {
1711 m_budget = 2 * m_budget;
1712 if (m_budget < 0)
1713 {
1714 m_budget = int.MaxValue;
1715 }
1716
1717 return;
1718 }
1719 }
1720 // Compute the new table size. We find the smallest integer larger than twice the previous table size, and not divisible by
1721 // 2,3,5 or 7. We can consider a different table-sizing policy in the future.
1722 int newLength = 0;
1723 bool maximizeTableSize = false;
1724 try
1725 {
1726 checked
1727 {
1728 // Double the size of the buckets table and add one, so that we have an odd integer.
1729 newLength = tables.m_buckets.Length * 2 + 1;
1730
1731 // Now, we only need to check odd integers, and find the first that is not divisible
1732 // by 3, 5 or 7.
1733 while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
1734 {
1735 newLength += 2;
1736 }
1737
1738 Assert(newLength % 2 != 0);
1739
1740 if (newLength > Array_ReferenceSources.MaxArrayLength)
1741 {
1742 maximizeTableSize = true;
1743 }
1744 }
1745 }
1746 catch (OverflowException)
1747 {
1748 maximizeTableSize = true;
1749 }
1750
1751 if (maximizeTableSize)
1752 {
1753 newLength = Array_ReferenceSources.MaxArrayLength;
1754
1755 // We want to make sure that GrowTable will not be called again, since table is at the maximum size.
1756 // To achieve that, we set the budget to int.MaxValue.
1757 //
1758 // (There is one special case that would allow GrowTable() to be called in the future:
1759 // calling Clear() on the ConcurrentDictionary will shrink the table and lower the budget.)
1760 m_budget = int.MaxValue;
1761 }
1762
1763 // Now acquire all other locks for the table
1764 AcquireLocks(1, tables.m_locks.Length, ref locksAcquired);
1765
1766 object[] newLocks = tables.m_locks;
1767
1768 // Add more locks
1769 if (m_growLockArray && tables.m_locks.Length < MAX_LOCK_NUMBER)
1770 {
1771 newLocks = new object[tables.m_locks.Length * 2];
1772 Array.Copy(tables.m_locks, newLocks, tables.m_locks.Length);
1773
1774 for (int i = tables.m_locks.Length; i < newLocks.Length; i++)
1775 {
1776 newLocks[i] = new object();
1777 }
1778 }
1779
1780 Node[] newBuckets = new Node[newLength];
1781 int[] newCountPerLock = new int[newLocks.Length];
1782
1783 // Copy all data into a new table, creating new nodes for all elements
1784 for (int i = 0; i < tables.m_buckets.Length; i++)
1785 {
1786 Node current = tables.m_buckets[i];
1787 while (current != null)
1788 {
1789 Node next = current.m_next;
1790 int newBucketNo, newLockNo;
1791 int nodeHashCode = current.m_hashcode;
1792
1793 if (regenerateHashKeys)
1794 {
1795 // Recompute the hash from the key
1796 nodeHashCode = newComparer.GetHashCode(current.m_key);
1797 }
1798
1799 GetBucketAndLockNo(nodeHashCode, out newBucketNo, out newLockNo, newBuckets.Length, newLocks.Length);
1800
1801 newBuckets[newBucketNo] = new Node(current.m_key, current.m_value, nodeHashCode, newBuckets[newBucketNo]);
1802
1803 checked
1804 {
1805 newCountPerLock[newLockNo]++;
1806 }
1807
1808 current = next;
1809 }
1810 }
1811
1812 // If this resize regenerated the hashkeys, increment the count
1813 if (regenerateHashKeys)
1814 {
1815 // We use unchecked here because we don't want to throw an exception if
1816 // an overflow happens
1817 unchecked
1818 {
1819 m_keyRehashCount++;
1820 }
1821 }
1822
1823 // Adjust the budget
1824 m_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
1825
1826 // Replace tables with the new versions
1827 m_tables = new Tables(newBuckets, newLocks, newCountPerLock, newComparer);
1828 }
1829 finally
1830 {
1831 // Release all locks that we took earlier
1832 ReleaseLocks(0, locksAcquired);
1833 }
1834 }
1835
1836 /// <summary>
1837 /// Computes the bucket and lock number for a particular key.
1838 /// </summary>
1839 private void GetBucketAndLockNo(
1840 int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
1841 {
1842 bucketNo = (hashcode & 0x7fffffff) % bucketCount;
1843 lockNo = bucketNo % lockCount;
1844
1845 Assert(bucketNo >= 0 && bucketNo < bucketCount);
1846 Assert(lockNo >= 0 && lockNo < lockCount);
1847 }
1848
1849 /// <summary>
1850 /// The number of concurrent writes for which to optimize by default.
1851 /// </summary>
1852 private static int DefaultConcurrencyLevel
1853 {
1854
1855 get { return DEFAULT_CONCURRENCY_MULTIPLIER * PlatformHelper.ProcessorCount; }
1856 }
1857
1858 /// <summary>
1859 /// Acquires all locks for this hash table, and increments locksAcquired by the number
1860 /// of locks that were successfully acquired. The locks are acquired in an increasing
1861 /// order.
1862 /// </summary>
1863 private void AcquireAllLocks(ref int locksAcquired)
1864 {
1865 #if !FEATURE_PAL && !FEATURE_CORECLR // PAL and CoreClr don't support eventing
1866 if (CDSCollectionETWBCLProvider.Log.IsEnabled())
1867 {
1868 CDSCollectionETWBCLProvider.Log.ConcurrentDictionary_AcquiringAllLocks(m_tables.m_buckets.Length);
1869 }
1870 #endif //!FEATURE_PAL && !FEATURE_CORECLR
1871
1872 // First, acquire lock 0
1873 AcquireLocks(0, 1, ref locksAcquired);
1874
1875 // Now that we have lock 0, the m_locks array will not change (i.e., grow),
1876 // and so we can safely read m_locks.Length.
1877 AcquireLocks(1, m_tables.m_locks.Length, ref locksAcquired);
1878 Assert(locksAcquired == m_tables.m_locks.Length);
1879 }
1880
1881 /// <summary>
1882 /// Acquires a contiguous range of locks for this hash table, and increments locksAcquired
1883 /// by the number of locks that were successfully acquired. The locks are acquired in an
1884 /// increasing order.
1885 /// </summary>
1886 private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
1887 {
1888 Assert(fromInclusive <= toExclusive);
1889 object[] locks = m_tables.m_locks;
1890
1891 for (int i = fromInclusive; i < toExclusive; i++)
1892 {
1893 bool lockTaken = false;
1894 try
1895 {
1896 #if CDS_COMPILE_JUST_THIS
1897 Monitor.Enter(m_tables.m_locks[i]);
1898 lockTaken = true;
1899 #else
1900 Monitor.Enter(locks[i], ref lockTaken);
1901 #endif
1902 }
1903 finally
1904 {
1905 if (lockTaken)
1906 {
1907 locksAcquired++;
1908 }
1909 }
1910 }
1911 }
1912
1913 /// <summary>
1914 /// Releases a contiguous range of locks.
1915 /// </summary>
1916 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
1917 private void ReleaseLocks(int fromInclusive, int toExclusive)
1918 {
1919 Assert(fromInclusive <= toExclusive);
1920
1921 for (int i = fromInclusive; i < toExclusive; i++)
1922 {
1923 Monitor.Exit(m_tables.m_locks[i]);
1924 }
1925 }
1926
1927 /// <summary>
1928 /// Gets a collection containing the keys in the dictionary.
1929 /// </summary>
1930 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
1931 private ReadOnlyCollection<TKey> GetKeys()
1932 {
1933 int locksAcquired = 0;
1934 try
1935 {
1936 AcquireAllLocks(ref locksAcquired);
1937 List<TKey> keys = new List<TKey>();
1938
1939 for (int i = 0; i < m_tables.m_buckets.Length; i++)
1940 {
1941 Node current = m_tables.m_buckets[i];
1942 while (current != null)
1943 {
1944 keys.Add(current.m_key);
1945 current = current.m_next;
1946 }
1947 }
1948
1949 return new ReadOnlyCollection<TKey>(keys);
1950 }
1951 finally
1952 {
1953 ReleaseLocks(0, locksAcquired);
1954 }
1955 }
1956
1957 /// <summary>
1958 /// Gets a collection containing the values in the dictionary.
1959 /// </summary>
1960 [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
1961 private ReadOnlyCollection<TValue> GetValues()
1962 {
1963 int locksAcquired = 0;
1964 try
1965 {
1966 AcquireAllLocks(ref locksAcquired);
1967 List<TValue> values = new List<TValue>();
1968
1969 for (int i = 0; i < m_tables.m_buckets.Length; i++)
1970 {
1971 Node current = m_tables.m_buckets[i];
1972 while (current != null)
1973 {
1974 values.Add(current.m_value);
1975 current = current.m_next;
1976 }
1977 }
1978
1979 return new ReadOnlyCollection<TValue>(values);
1980 }
1981 finally
1982 {
1983 ReleaseLocks(0, locksAcquired);
1984 }
1985 }
1986
1987 /// <summary>
1988 /// A helper method for asserts.
1989 /// </summary>
1990 [Conditional("DEBUG")]
1991 private void Assert(bool condition)
1992 {
1993 #if CDS_COMPILE_JUST_THIS
1994 if (!condition)
1995 {
1996 throw new Exception("Assertion failed.");
1997 }
1998 #else
1999 Contract.Assert(condition);
2000 #endif
2001 }
2002
2003 /// <summary>
2004 /// A helper function to obtain the string for a particular resource key.
2005 /// </summary>
2006 /// <param name="key"></param>
2007 /// <returns></returns>
2008 private string GetResource(string key)
2009 {
2010 Assert(key != null);
2011
2012 #if CDS_COMPILE_JUST_THIS
2013 return key;
2014 #else
2015 return Environment.GetResourceString(key);
2016 #endif
2017 }
2018
2019 /// <summary>
2020 /// A node in a singly-linked list representing a particular hash table bucket.
2021 /// </summary>
2022 private class Node
2023 {
2024 internal TKey m_key;
2025 internal TValue m_value;
2026 internal volatile Node m_next;
2027 internal int m_hashcode;
2028
2029 internal Node(TKey key, TValue value, int hashcode, Node next)
2030 {
2031 m_key = key;
2032 m_value = value;
2033 m_next = next;
2034 m_hashcode = hashcode;
2035 }
2036 }
2037
2038 /// <summary>
2039 /// A private class to represent enumeration over the dictionary that implements the
2040 /// IDictionaryEnumerator interface.
2041 /// </summary>
2042 private class DictionaryEnumerator : IDictionaryEnumerator
2043 {
2044 IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; // Enumerator over the dictionary.
2045
2046 internal DictionaryEnumerator(ConcurrentDictionary<TKey, TValue> dictionary)
2047 {
2048 m_enumerator = dictionary.GetEnumerator();
2049 }
2050
2051 public DictionaryEntry Entry
2052 {
2053 get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); }
2054 }
2055
2056 public object Key
2057 {
2058 get { return m_enumerator.Current.Key; }
2059 }
2060
2061 public object Value
2062 {
2063 get { return m_enumerator.Current.Value; }
2064 }
2065
2066 public object Current
2067 {
2068 get { return this.Entry; }
2069 }
2070
2071 public bool MoveNext()
2072 {
2073 return m_enumerator.MoveNext();
2074 }
2075
2076 public void Reset()
2077 {
2078 m_enumerator.Reset();
2079 }
2080 }
2081
2082 #if !FEATURE_CORECLR
2083 /// <summary>
2084 /// Get the data array to be serialized
2085 /// </summary>
2086 [OnSerializing]
2087 private void OnSerializing(StreamingContext context)
2088 {
2089 Tables tables = m_tables;
2090
2091 // save the data into the serialization array to be saved
2092 m_serializationArray = ToArray();
2093 m_serializationConcurrencyLevel = tables.m_locks.Length;
2094 m_serializationCapacity = tables.m_buckets.Length;
2095 m_comparer = (IEqualityComparer<TKey>)HashHelpers.GetEqualityComparerForSerialization(tables.m_comparer);
2096 }
2097
2098 /// <summary>
2099 /// Construct the dictionary from a previously serialized one
2100 /// </summary>
2101 [OnDeserialized]
2102 private void OnDeserialized(StreamingContext context)
2103 {
2104 KeyValuePair<TKey, TValue>[] array = m_serializationArray;
2105
2106 var buckets = new Node[m_serializationCapacity];
2107 var countPerLock = new int[m_serializationConcurrencyLevel];
2108
2109 var locks = new object[m_serializationConcurrencyLevel];
2110 for (int i = 0; i < locks.Length; i++)
2111 {
2112 locks[i] = new object();
2113 }
2114
2115 m_tables = new Tables(buckets, locks, countPerLock, m_comparer);
2116
2117 InitializeFromCollection(array);
2118 m_serializationArray = null;
2119
2120 }
2121 #endif
2122 }
2123 }