1 // ConcurrentDictionary.cs
3 // Copyright (c) 2009 Jérémie "Garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 using System.Threading;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Runtime.Serialization;
32 using System.Diagnostics;
34 namespace System.Collections.Concurrent
36 [DebuggerDisplay ("Count={Count}")]
37 [DebuggerTypeProxy (typeof (CollectionDebuggerView<,>))]
38 public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
39 ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
40 IDictionary, ICollection, IEnumerable
42 IEqualityComparer<TKey> comparer;
44 SplitOrderedList<TKey, KeyValuePair<TKey, TValue>> internalDictionary;
46 public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
50 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> collection)
51 : this (collection, EqualityComparer<TKey>.Default)
53 foreach (KeyValuePair<TKey, TValue> pair in collection)
54 Add (pair.Key, pair.Value);
57 public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
59 this.comparer = comparer;
60 this.internalDictionary = new SplitOrderedList<TKey, KeyValuePair<TKey, TValue>> (comparer);
63 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
66 foreach (KeyValuePair<TKey, TValue> pair in collection)
67 Add (pair.Key, pair.Value);
71 public ConcurrentDictionary (int concurrencyLevel, int capacity)
72 : this (EqualityComparer<TKey>.Default)
77 public ConcurrentDictionary (int concurrencyLevel,
78 IEnumerable<KeyValuePair<TKey, TValue>> collection,
79 IEqualityComparer<TKey> comparer)
80 : this (collection, comparer)
86 public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
92 void Add (TKey key, TValue value)
94 while (!TryAdd (key, value));
97 void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
102 public bool TryAdd (TKey key, TValue value)
104 return internalDictionary.Insert (Hash (key), key, Make (key, value));
107 void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
109 Add (pair.Key, pair.Value);
112 public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
114 return internalDictionary.InsertOrUpdate (Hash (key),
116 () => Make (key, addValueFactory (key)),
117 (e) => Make (key, updateValueFactory (key, e.Value))).Value;
120 public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
122 return AddOrUpdate (key, (_) => addValue, updateValueFactory);
125 TValue AddOrUpdate (TKey key, TValue addValue, TValue updateValue)
127 return internalDictionary.InsertOrUpdate (Hash (key),
129 Make (key, addValue),
130 Make (key, updateValue)).Value;
133 TValue GetValue (TKey key)
136 if (!TryGetValue (key, out temp))
137 throw new KeyNotFoundException (key.ToString ());
141 public bool TryGetValue (TKey key, out TValue value)
143 KeyValuePair<TKey, TValue> pair;
144 bool result = internalDictionary.Find (Hash (key), key, out pair);
150 public bool TryUpdate (TKey key, TValue newValue, TValue comparisonValue)
152 return internalDictionary.CompareExchange (Hash (key), key, Make (key, newValue), (e) => e.Value.Equals (comparisonValue));
155 public TValue this[TKey key] {
157 return GetValue (key);
160 AddOrUpdate (key, value, value);
164 public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
166 return internalDictionary.InsertOrGet (Hash (key), key, Make (key, default(TValue)), () => Make (key, valueFactory (key))).Value;
169 public TValue GetOrAdd (TKey key, TValue value)
171 return internalDictionary.InsertOrGet (Hash (key), key, Make (key, value), null).Value;
174 public bool TryRemove (TKey key, out TValue value)
176 KeyValuePair<TKey, TValue> data;
177 bool result = internalDictionary.Delete (Hash (key), key, out data);
182 bool Remove (TKey key)
186 return TryRemove (key, out dummy);
189 bool IDictionary<TKey, TValue>.Remove (TKey key)
194 bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
196 return Remove (pair.Key);
199 public bool ContainsKey (TKey key)
201 KeyValuePair<TKey, TValue> dummy;
202 return internalDictionary.Find (Hash (key), key, out dummy);
205 bool IDictionary.Contains (object key)
210 return ContainsKey ((TKey)key);
213 void IDictionary.Remove (object key)
221 object IDictionary.this [object key]
225 throw new ArgumentException ("key isn't of correct type", "key");
227 return this[(TKey)key];
230 if (!(key is TKey) || !(value is TValue))
231 throw new ArgumentException ("key or value aren't of correct type");
233 this[(TKey)key] = (TValue)value;
237 void IDictionary.Add (object key, object value)
239 if (!(key is TKey) || !(value is TValue))
240 throw new ArgumentException ("key or value aren't of correct type");
242 Add ((TKey)key, (TValue)value);
245 bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
247 return ContainsKey (pair.Key);
250 public KeyValuePair<TKey,TValue>[] ToArray ()
252 // This is most certainly not optimum but there is
253 // not a lot of possibilities
255 return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
261 internalDictionary = new SplitOrderedList<TKey, KeyValuePair<TKey, TValue>> (comparer);
266 return internalDictionary.Count;
270 public bool IsEmpty {
276 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
282 bool IDictionary.IsReadOnly {
288 public ICollection<TKey> Keys {
290 return GetPart<TKey> ((kvp) => kvp.Key);
294 public ICollection<TValue> Values {
296 return GetPart<TValue> ((kvp) => kvp.Value);
300 ICollection IDictionary.Keys {
302 return (ICollection)Keys;
306 ICollection IDictionary.Values {
308 return (ICollection)Values;
312 ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
314 List<T> temp = new List<T> ();
316 foreach (KeyValuePair<TKey, TValue> kvp in this)
317 temp.Add (extractor (kvp));
319 return temp.AsReadOnly ();
322 void ICollection.CopyTo (Array array, int startIndex)
324 KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
328 CopyTo (arr, startIndex, Count);
331 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
333 CopyTo (array, startIndex, Count);
336 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
338 CopyTo (array, startIndex);
341 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
343 foreach (var kvp in this) {
344 array [startIndex++] = kvp;
351 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
353 return GetEnumeratorInternal ();
356 IEnumerator IEnumerable.GetEnumerator ()
358 return (IEnumerator)GetEnumeratorInternal ();
361 IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
363 return internalDictionary.GetEnumerator ();
366 IDictionaryEnumerator IDictionary.GetEnumerator ()
368 return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
371 class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
373 IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
375 public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
377 this.internalEnum = internalEnum;
380 public bool MoveNext ()
382 return internalEnum.MoveNext ();
387 internalEnum.Reset ();
390 public object Current {
396 public DictionaryEntry Entry {
398 KeyValuePair<TKey, TValue> current = internalEnum.Current;
399 return new DictionaryEntry (current.Key, current.Value);
405 return internalEnum.Current.Key;
409 public object Value {
411 return internalEnum.Current.Value;
416 object ICollection.SyncRoot {
422 bool IDictionary.IsFixedSize {
428 bool ICollection.IsSynchronized {
432 static KeyValuePair<U, V> Make<U, V> (U key, V value)
434 return new KeyValuePair<U, V> (key, value);
439 return (uint)comparer.GetHashCode (key);