ConcurrentDictionary.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // ConcurrentDictionary.cs
  2. //
  3. // Copyright (c) 2009 Jérémie "Garuma" Laval
  4. //
  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:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  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
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0 || BOOTSTRAP_NET_4_0
  25. using System;
  26. using System.Threading;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.Runtime.Serialization;
  30. using System.Diagnostics;
  31. namespace System.Collections.Concurrent
  32. {
  33. [DebuggerDisplay ("Count={Count}")]
  34. [DebuggerTypeProxy (typeof (CollectionDebuggerView<,>))]
  35. public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
  36. ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
  37. IDictionary, ICollection, IEnumerable
  38. {
  39. IEqualityComparer<TKey> comparer;
  40. SplitOrderedList<KeyValuePair<TKey, TValue>> internalDictionary = new SplitOrderedList<KeyValuePair<TKey, TValue>> ();
  41. public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
  42. {
  43. }
  44. public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
  45. : this (values, EqualityComparer<TKey>.Default)
  46. {
  47. foreach (KeyValuePair<TKey, TValue> pair in values)
  48. Add (pair.Key, pair.Value);
  49. }
  50. public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
  51. {
  52. this.comparer = comparer;
  53. }
  54. public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
  55. : this (comparer)
  56. {
  57. foreach (KeyValuePair<TKey, TValue> pair in values)
  58. Add (pair.Key, pair.Value);
  59. }
  60. // Parameters unused
  61. public ConcurrentDictionary (int concurrencyLevel, int capacity)
  62. : this (EqualityComparer<TKey>.Default)
  63. {
  64. }
  65. public ConcurrentDictionary (int concurrencyLevel,
  66. IEnumerable<KeyValuePair<TKey, TValue>> values,
  67. IEqualityComparer<TKey> comparer)
  68. : this (values, comparer)
  69. {
  70. }
  71. // Parameters unused
  72. public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
  73. : this (comparer)
  74. {
  75. }
  76. void Add (TKey key, TValue value)
  77. {
  78. while (!TryAdd (key, value));
  79. }
  80. void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
  81. {
  82. Add (key, value);
  83. }
  84. public bool TryAdd (TKey key, TValue value)
  85. {
  86. return internalDictionary.Insert (Hash (key), Make (key, value));
  87. }
  88. void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
  89. {
  90. Add (pair.Key, pair.Value);
  91. }
  92. public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
  93. {
  94. return internalDictionary.InsertOrUpdate (Hash (key),
  95. () => Make (key, addValueFactory (key)),
  96. (e) => Make (key, updateValueFactory (key, e.Value))).Value;
  97. }
  98. public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
  99. {
  100. return AddOrUpdate (key, (_) => addValue, updateValueFactory);
  101. }
  102. TValue AddOrUpdate (TKey key, TValue addValue, TValue updateValue)
  103. {
  104. return internalDictionary.InsertOrUpdate (Hash (key),
  105. Make (key, addValue),
  106. Make (key, updateValue)).Value;
  107. }
  108. TValue GetValue (TKey key)
  109. {
  110. TValue temp;
  111. if (!TryGetValue (key, out temp))
  112. // TODO: find a correct Exception
  113. throw new ArgumentException ("Not a valid key for this dictionary", "key");
  114. return temp;
  115. }
  116. public bool TryGetValue (TKey key, out TValue value)
  117. {
  118. KeyValuePair<TKey, TValue> pair;
  119. bool result = internalDictionary.Find (Hash (key), out pair);
  120. value = pair.Value;
  121. return result;
  122. }
  123. public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
  124. {
  125. return internalDictionary.CompareExchange (Hash (key), Make (key, newValue), (e) => e.Value.Equals (comparand));
  126. }
  127. public TValue this[TKey key] {
  128. get {
  129. return GetValue (key);
  130. }
  131. set {
  132. AddOrUpdate (key, value, value);
  133. }
  134. }
  135. public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
  136. {
  137. return internalDictionary.InsertOrGet (Hash (key), Make (key, default(TValue)), () => Make (key, valueFactory (key))).Value;
  138. }
  139. public TValue GetOrAdd (TKey key, TValue value)
  140. {
  141. return internalDictionary.InsertOrGet (Hash (key), Make (key, value), null).Value;
  142. }
  143. public bool TryRemove (TKey key, out TValue value)
  144. {
  145. KeyValuePair<TKey, TValue> data;
  146. bool result = internalDictionary.Delete (Hash (key), out data);
  147. value = data.Value;
  148. return result;
  149. }
  150. bool Remove (TKey key)
  151. {
  152. TValue dummy;
  153. return TryRemove (key, out dummy);
  154. }
  155. bool IDictionary<TKey, TValue>.Remove (TKey key)
  156. {
  157. return Remove (key);
  158. }
  159. bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
  160. {
  161. return Remove (pair.Key);
  162. }
  163. public bool ContainsKey (TKey key)
  164. {
  165. KeyValuePair<TKey, TValue> dummy;
  166. return internalDictionary.Find (Hash (key), out dummy);
  167. }
  168. bool IDictionary.Contains (object key)
  169. {
  170. if (!(key is TKey))
  171. return false;
  172. return ContainsKey ((TKey)key);
  173. }
  174. void IDictionary.Remove (object key)
  175. {
  176. if (!(key is TKey))
  177. return;
  178. Remove ((TKey)key);
  179. }
  180. object IDictionary.this [object key]
  181. {
  182. get {
  183. if (!(key is TKey))
  184. throw new ArgumentException ("key isn't of correct type", "key");
  185. return this[(TKey)key];
  186. }
  187. set {
  188. if (!(key is TKey) || !(value is TValue))
  189. throw new ArgumentException ("key or value aren't of correct type");
  190. this[(TKey)key] = (TValue)value;
  191. }
  192. }
  193. void IDictionary.Add (object key, object value)
  194. {
  195. if (!(key is TKey) || !(value is TValue))
  196. throw new ArgumentException ("key or value aren't of correct type");
  197. Add ((TKey)key, (TValue)value);
  198. }
  199. bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
  200. {
  201. return ContainsKey (pair.Key);
  202. }
  203. public KeyValuePair<TKey,TValue>[] ToArray ()
  204. {
  205. // This is most certainly not optimum but there is
  206. // not a lot of possibilities
  207. return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
  208. }
  209. public void Clear()
  210. {
  211. // Pronk
  212. internalDictionary = new SplitOrderedList<KeyValuePair<TKey, TValue>> ();
  213. }
  214. public int Count {
  215. get {
  216. return internalDictionary.Count;
  217. }
  218. }
  219. public bool IsEmpty {
  220. get {
  221. return Count == 0;
  222. }
  223. }
  224. bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
  225. get {
  226. return false;
  227. }
  228. }
  229. bool IDictionary.IsReadOnly {
  230. get {
  231. return false;
  232. }
  233. }
  234. public ICollection<TKey> Keys {
  235. get {
  236. return GetPart<TKey> ((kvp) => kvp.Key);
  237. }
  238. }
  239. public ICollection<TValue> Values {
  240. get {
  241. return GetPart<TValue> ((kvp) => kvp.Value);
  242. }
  243. }
  244. ICollection IDictionary.Keys {
  245. get {
  246. return (ICollection)Keys;
  247. }
  248. }
  249. ICollection IDictionary.Values {
  250. get {
  251. return (ICollection)Values;
  252. }
  253. }
  254. ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
  255. {
  256. List<T> temp = new List<T> ();
  257. foreach (KeyValuePair<TKey, TValue> kvp in this)
  258. temp.Add (extractor (kvp));
  259. return temp.AsReadOnly ();
  260. }
  261. void ICollection.CopyTo (Array array, int startIndex)
  262. {
  263. KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
  264. if (arr == null)
  265. return;
  266. CopyTo (arr, startIndex, Count);
  267. }
  268. void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
  269. {
  270. CopyTo (array, startIndex, Count);
  271. }
  272. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
  273. {
  274. CopyTo (array, startIndex);
  275. }
  276. void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
  277. {
  278. foreach (var kvp in this) {
  279. array [startIndex++] = kvp;
  280. if (--num <= 0)
  281. return;
  282. }
  283. }
  284. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
  285. {
  286. return GetEnumeratorInternal ();
  287. }
  288. IEnumerator IEnumerable.GetEnumerator ()
  289. {
  290. return (IEnumerator)GetEnumeratorInternal ();
  291. }
  292. IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
  293. {
  294. return internalDictionary.GetEnumerator ();
  295. }
  296. IDictionaryEnumerator IDictionary.GetEnumerator ()
  297. {
  298. return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
  299. }
  300. class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
  301. {
  302. IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
  303. public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
  304. {
  305. this.internalEnum = internalEnum;
  306. }
  307. public bool MoveNext ()
  308. {
  309. return internalEnum.MoveNext ();
  310. }
  311. public void Reset ()
  312. {
  313. internalEnum.Reset ();
  314. }
  315. public object Current {
  316. get {
  317. return Entry;
  318. }
  319. }
  320. public DictionaryEntry Entry {
  321. get {
  322. KeyValuePair<TKey, TValue> current = internalEnum.Current;
  323. return new DictionaryEntry (current.Key, current.Value);
  324. }
  325. }
  326. public object Key {
  327. get {
  328. return internalEnum.Current.Key;
  329. }
  330. }
  331. public object Value {
  332. get {
  333. return internalEnum.Current.Value;
  334. }
  335. }
  336. }
  337. object ICollection.SyncRoot {
  338. get {
  339. return this;
  340. }
  341. }
  342. bool IDictionary.IsFixedSize {
  343. get {
  344. return false;
  345. }
  346. }
  347. bool ICollection.IsSynchronized {
  348. get { return true; }
  349. }
  350. static KeyValuePair<U, V> Make<U, V> (U key, V value)
  351. {
  352. return new KeyValuePair<U, V> (key, value);
  353. }
  354. uint Hash (TKey key)
  355. {
  356. return (uint)comparer.GetHashCode (key);
  357. }
  358. }
  359. }
  360. #endif