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)
55 public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
57 this.comparer = comparer;
58 this.internalDictionary = new SplitOrderedList<TKey, KeyValuePair<TKey, TValue>> (comparer);
61 public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer)
64 foreach (KeyValuePair<TKey, TValue> pair in collection)
65 Add (pair.Key, pair.Value);
69 public ConcurrentDictionary (int concurrencyLevel, int capacity)
70 : this (EqualityComparer<TKey>.Default)
75 public ConcurrentDictionary (int concurrencyLevel,
76 IEnumerable<KeyValuePair<TKey, TValue>> collection,
77 IEqualityComparer<TKey> comparer)
78 : this (collection, comparer)
84 public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
90 void Add (TKey key, TValue value)
92 while (!TryAdd (key, value));
95 void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
100 public bool TryAdd (TKey key, TValue value)
102 return internalDictionary.Insert (Hash (key), key, Make (key, value));
105 void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
107 Add (pair.Key, pair.Value);
110 public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
112 return internalDictionary.InsertOrUpdate (Hash (key),
114 () => Make (key, addValueFactory (key)),
115 (e) => Make (key, updateValueFactory (key, e.Value))).Value;
118 public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
120 return AddOrUpdate (key, (_) => addValue, updateValueFactory);
123 TValue AddOrUpdate (TKey key, TValue addValue, TValue updateValue)
125 return internalDictionary.InsertOrUpdate (Hash (key),
127 Make (key, addValue),
128 Make (key, updateValue)).Value;
131 TValue GetValue (TKey key)
134 if (!TryGetValue (key, out temp))
135 throw new KeyNotFoundException (key.ToString ());
139 public bool TryGetValue (TKey key, out TValue value)
141 KeyValuePair<TKey, TValue> pair;
142 bool result = internalDictionary.Find (Hash (key), key, out pair);
148 public bool TryUpdate (TKey key, TValue newValue, TValue comparisonValue)
150 return internalDictionary.CompareExchange (Hash (key), key, Make (key, newValue), (e) => e.Value.Equals (comparisonValue));
153 public TValue this[TKey key] {
155 return GetValue (key);
158 AddOrUpdate (key, value, value);
162 public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
164 return internalDictionary.InsertOrGet (Hash (key), key, Make (key, default(TValue)), () => Make (key, valueFactory (key))).Value;
167 public TValue GetOrAdd (TKey key, TValue value)
169 return internalDictionary.InsertOrGet (Hash (key), key, Make (key, value), null).Value;
172 public bool TryRemove (TKey key, out TValue value)
174 KeyValuePair<TKey, TValue> data;
175 bool result = internalDictionary.Delete (Hash (key), key, out data);
180 bool Remove (TKey key)
184 return TryRemove (key, out dummy);
187 bool IDictionary<TKey, TValue>.Remove (TKey key)
192 bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
194 return Remove (pair.Key);
197 public bool ContainsKey (TKey key)
199 KeyValuePair<TKey, TValue> dummy;
200 return internalDictionary.Find (Hash (key), key, out dummy);
203 bool IDictionary.Contains (object key)
208 return ContainsKey ((TKey)key);
211 void IDictionary.Remove (object key)
219 object IDictionary.this [object key]
223 throw new ArgumentException ("key isn't of correct type", "key");
225 return this[(TKey)key];
228 if (!(key is TKey) || !(value is TValue))
229 throw new ArgumentException ("key or value aren't of correct type");
231 this[(TKey)key] = (TValue)value;
235 void IDictionary.Add (object key, object value)
237 if (!(key is TKey) || !(value is TValue))
238 throw new ArgumentException ("key or value aren't of correct type");
240 Add ((TKey)key, (TValue)value);
243 bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
245 return ContainsKey (pair.Key);
248 public KeyValuePair<TKey,TValue>[] ToArray ()
250 // This is most certainly not optimum but there is
251 // not a lot of possibilities
253 return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
259 internalDictionary = new SplitOrderedList<TKey, KeyValuePair<TKey, TValue>> (comparer);
264 return internalDictionary.Count;
268 public bool IsEmpty {
274 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
280 bool IDictionary.IsReadOnly {
286 public ICollection<TKey> Keys {
288 return GetPart<TKey> ((kvp) => kvp.Key);
292 public ICollection<TValue> Values {
294 return GetPart<TValue> ((kvp) => kvp.Value);
298 ICollection IDictionary.Keys {
300 return (ICollection)Keys;
304 ICollection IDictionary.Values {
306 return (ICollection)Values;
310 ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
312 List<T> temp = new List<T> ();
314 foreach (KeyValuePair<TKey, TValue> kvp in this)
315 temp.Add (extractor (kvp));
317 return temp.AsReadOnly ();
320 void ICollection.CopyTo (Array array, int startIndex)
322 KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
326 CopyTo (arr, startIndex, Count);
329 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
331 CopyTo (array, startIndex, Count);
334 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
336 CopyTo (array, startIndex);
339 void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
341 foreach (var kvp in this) {
342 array [startIndex++] = kvp;
349 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
351 return GetEnumeratorInternal ();
354 IEnumerator IEnumerable.GetEnumerator ()
356 return (IEnumerator)GetEnumeratorInternal ();
359 IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
361 return internalDictionary.GetEnumerator ();
364 IDictionaryEnumerator IDictionary.GetEnumerator ()
366 return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
369 class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
371 IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
373 public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
375 this.internalEnum = internalEnum;
378 public bool MoveNext ()
380 return internalEnum.MoveNext ();
385 internalEnum.Reset ();
388 public object Current {
394 public DictionaryEntry Entry {
396 KeyValuePair<TKey, TValue> current = internalEnum.Current;
397 return new DictionaryEntry (current.Key, current.Value);
403 return internalEnum.Current.Key;
407 public object Value {
409 return internalEnum.Current.Value;
414 object ICollection.SyncRoot {
420 bool IDictionary.IsFixedSize {
426 bool ICollection.IsSynchronized {
430 static KeyValuePair<U, V> Make<U, V> (U key, V value)
432 return new KeyValuePair<U, V> (key, value);
437 return (uint)comparer.GetHashCode (key);