BlockingCollection.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #if NET_4_0
  2. // BlockingCollection.cs
  3. //
  4. // Copyright (c) 2008 Jérémie "Garuma" Laval
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. //
  25. using System;
  26. using System.Threading;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. namespace System.Collections.Concurrent
  31. {
  32. public class BlockingCollection<T> : IEnumerable<T>, ICollection, IEnumerable, IDisposable
  33. {
  34. readonly IProducerConsumerCollection<T> underlyingColl;
  35. readonly int upperBound;
  36. readonly SpinWait sw = new SpinWait ();
  37. AtomicBoolean isComplete;
  38. long completeId;
  39. long addId = long.MinValue;
  40. long removeId = long.MinValue;
  41. #region ctors
  42. public BlockingCollection ()
  43. : this (new ConcurrentQueue<T> (), -1)
  44. {
  45. }
  46. public BlockingCollection (int upperBound)
  47. : this (new ConcurrentQueue<T> (), upperBound)
  48. {
  49. }
  50. public BlockingCollection (IProducerConsumerCollection<T> underlyingColl)
  51. : this (underlyingColl, -1)
  52. {
  53. }
  54. public BlockingCollection (IProducerConsumerCollection<T> underlyingColl, int upperBound)
  55. {
  56. this.underlyingColl = underlyingColl;
  57. this.upperBound = upperBound;
  58. this.isComplete = new AtomicBoolean ();
  59. }
  60. #endregion
  61. #region Add & Remove (+ Try)
  62. public void Add (T item)
  63. {
  64. Add (item, null);
  65. }
  66. public void Add (T item, CancellationToken token)
  67. {
  68. Add (item, () => token.IsCancellationRequested);
  69. }
  70. void Add (T item, Func<bool> cancellationFunc)
  71. {
  72. while (true) {
  73. long cachedAddId = addId;
  74. long cachedRemoveId = removeId;
  75. if (upperBound != -1) {
  76. if (cachedAddId - cachedRemoveId > upperBound) {
  77. Block ();
  78. continue;
  79. }
  80. }
  81. // Check our transaction id against completed stored one
  82. if (isComplete.Value && cachedAddId >= completeId)
  83. throw new InvalidOperationException ("The BlockingCollection<T> has"
  84. + " been marked as complete with regards to additions.");
  85. if (Interlocked.CompareExchange (ref addId, cachedAddId + 1, cachedAddId) == cachedAddId)
  86. break;
  87. if (cancellationFunc != null && cancellationFunc ())
  88. throw new OperationCanceledException ("CancellationToken triggered");
  89. }
  90. if (!underlyingColl.TryAdd (item))
  91. throw new InvalidOperationException ("The underlying collection didn't accept the item.");
  92. }
  93. public T Take ()
  94. {
  95. return Take (null);
  96. }
  97. public T Take (CancellationToken token)
  98. {
  99. return Take (() => token.IsCancellationRequested);
  100. }
  101. T Take (Func<bool> cancellationFunc)
  102. {
  103. while (true) {
  104. long cachedRemoveId = removeId;
  105. long cachedAddId = addId;
  106. // Empty case
  107. if (cachedRemoveId == cachedAddId) {
  108. if (isComplete.Value && cachedRemoveId >= completeId)
  109. throw new OperationCanceledException ("The BlockingCollection<T> has"
  110. + " been marked as complete with regards to additions.");
  111. Block ();
  112. continue;
  113. }
  114. if (Interlocked.CompareExchange (ref removeId, cachedRemoveId + 1, cachedRemoveId) == cachedRemoveId)
  115. break;
  116. if (cancellationFunc != null && cancellationFunc ())
  117. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  118. }
  119. T item;
  120. while (!underlyingColl.TryTake (out item));
  121. return item;
  122. }
  123. public bool TryAdd (T item)
  124. {
  125. return TryAdd (item, null, null);
  126. }
  127. bool TryAdd (T item, Func<bool> contFunc, CancellationToken? token)
  128. {
  129. do {
  130. if (token.HasValue && token.Value.IsCancellationRequested)
  131. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  132. long cachedAddId = addId;
  133. long cachedRemoveId = removeId;
  134. if (upperBound != -1) {
  135. if (cachedAddId - cachedRemoveId > upperBound) {
  136. continue;
  137. }
  138. }
  139. // Check our transaction id against completed stored one
  140. if (isComplete.Value && cachedAddId >= completeId)
  141. throw new InvalidOperationException ("The BlockingCollection<T> has"
  142. + " been marked as complete with regards to additions.");
  143. if (Interlocked.CompareExchange (ref addId, cachedAddId + 1, cachedAddId) != cachedAddId)
  144. continue;
  145. if (!underlyingColl.TryAdd (item))
  146. throw new InvalidOperationException ("The underlying collection didn't accept the item.");
  147. return true;
  148. } while (contFunc != null && contFunc ());
  149. return false;
  150. }
  151. public bool TryAdd (T item, TimeSpan ts)
  152. {
  153. return TryAdd (item, (int)ts.TotalMilliseconds);
  154. }
  155. public bool TryAdd (T item, int millisecondsTimeout)
  156. {
  157. Stopwatch sw = Stopwatch.StartNew ();
  158. return TryAdd (item, () => sw.ElapsedMilliseconds < millisecondsTimeout, null);
  159. }
  160. public bool TryAdd (T item, int millisecondsTimeout, CancellationToken token)
  161. {
  162. Stopwatch sw = Stopwatch.StartNew ();
  163. return TryAdd (item, () => sw.ElapsedMilliseconds < millisecondsTimeout, token);
  164. }
  165. public bool TryTake (out T item)
  166. {
  167. return TryTake (out item, null, null);
  168. }
  169. bool TryTake (out T item, Func<bool> contFunc, CancellationToken? token)
  170. {
  171. item = default (T);
  172. do {
  173. if (token.HasValue && token.Value.IsCancellationRequested)
  174. throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
  175. long cachedRemoveId = removeId;
  176. long cachedAddId = addId;
  177. // Empty case
  178. if (cachedRemoveId == cachedAddId) {
  179. if (isComplete.Value && cachedRemoveId >= completeId)
  180. continue;
  181. continue;
  182. }
  183. if (Interlocked.CompareExchange (ref removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
  184. continue;
  185. return underlyingColl.TryTake (out item);
  186. } while (contFunc != null && contFunc ());
  187. return false;
  188. }
  189. public bool TryTake (out T item, TimeSpan ts)
  190. {
  191. return TryTake (out item, (int)ts.TotalMilliseconds);
  192. }
  193. public bool TryTake (out T item, int millisecondsTimeout)
  194. {
  195. item = default (T);
  196. Stopwatch sw = Stopwatch.StartNew ();
  197. return TryTake (out item, () => sw.ElapsedMilliseconds < millisecondsTimeout, null);
  198. }
  199. public bool TryTake (out T item, int millisecondsTimeout, CancellationToken token)
  200. {
  201. item = default (T);
  202. Stopwatch sw = Stopwatch.StartNew ();
  203. return TryTake (out item, () => sw.ElapsedMilliseconds < millisecondsTimeout, token);
  204. }
  205. #endregion
  206. #region static methods
  207. static void CheckArray (BlockingCollection<T>[] collections)
  208. {
  209. if (collections == null)
  210. throw new ArgumentNullException ("collections");
  211. if (collections.Length == 0 || IsThereANullElement (collections))
  212. throw new ArgumentException ("The collections argument is a 0-length array or contains a null element.", "collections");
  213. }
  214. static bool IsThereANullElement (BlockingCollection<T>[] collections)
  215. {
  216. foreach (BlockingCollection<T> e in collections)
  217. if (e == null)
  218. return true;
  219. return false;
  220. }
  221. public static int AddToAny (BlockingCollection<T>[] collections, T item)
  222. {
  223. CheckArray (collections);
  224. int index = 0;
  225. foreach (var coll in collections) {
  226. try {
  227. coll.Add (item);
  228. return index;
  229. } catch {}
  230. index++;
  231. }
  232. return -1;
  233. }
  234. public static int AddToAny (BlockingCollection<T>[] collections, T item, CancellationToken token)
  235. {
  236. CheckArray (collections);
  237. int index = 0;
  238. foreach (var coll in collections) {
  239. try {
  240. coll.Add (item, token);
  241. return index;
  242. } catch {}
  243. index++;
  244. }
  245. return -1;
  246. }
  247. public static int TryAddToAny (BlockingCollection<T>[] collections, T item)
  248. {
  249. CheckArray (collections);
  250. int index = 0;
  251. foreach (var coll in collections) {
  252. if (coll.TryAdd (item))
  253. return index;
  254. index++;
  255. }
  256. return -1;
  257. }
  258. public static int TryAddToAny (BlockingCollection<T>[] collections, T item, TimeSpan ts)
  259. {
  260. CheckArray (collections);
  261. int index = 0;
  262. foreach (var coll in collections) {
  263. if (coll.TryAdd (item, ts))
  264. return index;
  265. index++;
  266. }
  267. return -1;
  268. }
  269. public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout)
  270. {
  271. CheckArray (collections);
  272. int index = 0;
  273. foreach (var coll in collections) {
  274. if (coll.TryAdd (item, millisecondsTimeout))
  275. return index;
  276. index++;
  277. }
  278. return -1;
  279. }
  280. public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout,
  281. CancellationToken token)
  282. {
  283. CheckArray (collections);
  284. int index = 0;
  285. foreach (var coll in collections) {
  286. if (coll.TryAdd (item, millisecondsTimeout, token))
  287. return index;
  288. index++;
  289. }
  290. return -1;
  291. }
  292. public static int TakeFromAny (BlockingCollection<T>[] collections, out T item)
  293. {
  294. item = default (T);
  295. CheckArray (collections);
  296. int index = 0;
  297. foreach (var coll in collections) {
  298. try {
  299. item = coll.Take ();
  300. return index;
  301. } catch {}
  302. index++;
  303. }
  304. return -1;
  305. }
  306. public static int TakeFromAny (BlockingCollection<T>[] collections, out T item, CancellationToken token)
  307. {
  308. item = default (T);
  309. CheckArray (collections);
  310. int index = 0;
  311. foreach (var coll in collections) {
  312. try {
  313. item = coll.Take (token);
  314. return index;
  315. } catch {}
  316. index++;
  317. }
  318. return -1;
  319. }
  320. public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item)
  321. {
  322. item = default (T);
  323. CheckArray (collections);
  324. int index = 0;
  325. foreach (var coll in collections) {
  326. if (coll.TryTake (out item))
  327. return index;
  328. index++;
  329. }
  330. return -1;
  331. }
  332. public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, TimeSpan ts)
  333. {
  334. item = default (T);
  335. CheckArray (collections);
  336. int index = 0;
  337. foreach (var coll in collections) {
  338. if (coll.TryTake (out item, ts))
  339. return index;
  340. index++;
  341. }
  342. return -1;
  343. }
  344. public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout)
  345. {
  346. item = default (T);
  347. CheckArray (collections);
  348. int index = 0;
  349. foreach (var coll in collections) {
  350. if (coll.TryTake (out item, millisecondsTimeout))
  351. return index;
  352. index++;
  353. }
  354. return -1;
  355. }
  356. public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout,
  357. CancellationToken token)
  358. {
  359. item = default (T);
  360. CheckArray (collections);
  361. int index = 0;
  362. foreach (var coll in collections) {
  363. if (coll.TryTake (out item, millisecondsTimeout, token))
  364. return index;
  365. index++;
  366. }
  367. return -1;
  368. }
  369. #endregion
  370. public void CompleteAdding ()
  371. {
  372. // No further add beside that point
  373. completeId = addId;
  374. isComplete.Value = true;
  375. }
  376. void ICollection.CopyTo (Array array, int index)
  377. {
  378. underlyingColl.CopyTo (array, index);
  379. }
  380. public void CopyTo (T[] array, int index)
  381. {
  382. underlyingColl.CopyTo (array, index);
  383. }
  384. public IEnumerable<T> GetConsumingEnumerable ()
  385. {
  386. return GetConsumingEnumerable (Take);
  387. }
  388. public IEnumerable<T> GetConsumingEnumerable (CancellationToken token)
  389. {
  390. return GetConsumingEnumerable (() => Take (token));
  391. }
  392. IEnumerable<T> GetConsumingEnumerable (Func<T> getFunc)
  393. {
  394. while (true) {
  395. T item = default (T);
  396. try {
  397. item = getFunc ();
  398. } catch {
  399. break;
  400. }
  401. yield return item;
  402. }
  403. }
  404. IEnumerator IEnumerable.GetEnumerator ()
  405. {
  406. return ((IEnumerable)underlyingColl).GetEnumerator ();
  407. }
  408. IEnumerator<T> IEnumerable<T>.GetEnumerator ()
  409. {
  410. return ((IEnumerable<T>)underlyingColl).GetEnumerator ();
  411. }
  412. public void Dispose ()
  413. {
  414. }
  415. protected virtual void Dispose (bool managedRes)
  416. {
  417. }
  418. public T[] ToArray ()
  419. {
  420. return underlyingColl.ToArray ();
  421. }
  422. // Method used to stall the thread for a limited period of time before retrying an operation
  423. void Block ()
  424. {
  425. sw.SpinOnce ();
  426. }
  427. public int BoundedCapacity {
  428. get {
  429. return upperBound;
  430. }
  431. }
  432. public int Count {
  433. get {
  434. return underlyingColl.Count;
  435. }
  436. }
  437. public bool IsAddingCompleted {
  438. get {
  439. return isComplete.Value;
  440. }
  441. }
  442. public bool IsCompleted {
  443. get {
  444. return isComplete.Value && addId == removeId;
  445. }
  446. }
  447. object ICollection.SyncRoot {
  448. get {
  449. return underlyingColl.SyncRoot;
  450. }
  451. }
  452. bool ICollection.IsSynchronized {
  453. get {
  454. return underlyingColl.IsSynchronized;
  455. }
  456. }
  457. }
  458. }
  459. #endif