1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
|
//
// BlockingCollection.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if NET_4_0
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Collections.Concurrent
{
[ComVisible (false)]
[DebuggerDisplay ("Count={Count}")]
[DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
public class BlockingCollection<T> : IEnumerable<T>, ICollection, IEnumerable, IDisposable
{
const int spinCount = 5;
readonly IProducerConsumerCollection<T> underlyingColl;
/* These events are used solely for the purpose of having an optimized sleep cycle when
* the BlockingCollection have to wait on an external event (Add or Remove for instance)
*/
ManualResetEventSlim mreAdd = new ManualResetEventSlim (true);
ManualResetEventSlim mreRemove = new ManualResetEventSlim (true);
AtomicBoolean isComplete;
readonly int upperBound;
int completeId;
/* The whole idea of the collection is to use these two long values in a transactional
* way to track and manage the actual data inside the underlying lock-free collection
* instead of directly working with it or using external locking.
*
* They are manipulated with CAS and are guaranteed to increase over time and use
* of the instance thus preventing ABA problems.
*/
int addId = int.MinValue;
int removeId = int.MinValue;
/* For time based operations, we share this instance of Stopwatch and base calculation
on a time offset at each of these method call */
static Stopwatch watch = Stopwatch.StartNew ();
#region ctors
public BlockingCollection ()
: this (new ConcurrentQueue<T> (), -1)
{
}
public BlockingCollection (int boundedCapacity)
: this (new ConcurrentQueue<T> (), boundedCapacity)
{
}
public BlockingCollection (IProducerConsumerCollection<T> collection)
: this (collection, -1)
{
}
public BlockingCollection (IProducerConsumerCollection<T> collection, int boundedCapacity)
{
this.underlyingColl = collection;
this.upperBound = boundedCapacity;
this.isComplete = new AtomicBoolean ();
}
#endregion
#region Add & Remove (+ Try)
public void Add (T item)
{
Add (item, CancellationToken.None);
}
public void Add (T item, CancellationToken cancellationToken)
{
TryAdd (item, -1, cancellationToken);
}
public bool TryAdd (T item)
{
return TryAdd (item, 0, CancellationToken.None);
}
public bool TryAdd (T item, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException ("millisecondsTimeout");
long start = millisecondsTimeout == -1 ? 0 : watch.ElapsedMilliseconds;
SpinWait sw = new SpinWait ();
do {
cancellationToken.ThrowIfCancellationRequested ();
int cachedAddId = addId;
int cachedRemoveId = removeId;
int itemsIn = cachedAddId - cachedRemoveId;
// Check our transaction id against completed stored one
if (isComplete.Value && cachedAddId >= completeId)
ThrowCompleteException ();
// If needed, we check and wait that the collection isn't full
if (upperBound != -1 && itemsIn >= upperBound) {
if (millisecondsTimeout == 0)
return false;
if (sw.Count <= spinCount) {
sw.SpinOnce ();
} else {
mreRemove.Reset ();
if (cachedRemoveId != removeId || cachedAddId != addId) {
mreRemove.Set ();
continue;
}
mreRemove.Wait (ComputeTimeout (millisecondsTimeout, start), cancellationToken);
}
continue;
}
// Validate the steps we have been doing until now
if (Interlocked.CompareExchange (ref addId, cachedAddId + 1, cachedAddId) != cachedAddId)
continue;
// We have a slot reserved in the underlying collection, try to take it
if (!underlyingColl.TryAdd (item))
throw new InvalidOperationException ("The underlying collection didn't accept the item.");
// Wake up process that may have been sleeping
mreAdd.Set ();
return true;
} while (millisecondsTimeout == -1 || (watch.ElapsedMilliseconds - start) < millisecondsTimeout);
return false;
}
public bool TryAdd (T item, TimeSpan timeout)
{
return TryAdd (item, (int)timeout.TotalMilliseconds);
}
public bool TryAdd (T item, int millisecondsTimeout)
{
return TryAdd (item, millisecondsTimeout, CancellationToken.None);
}
public T Take ()
{
return Take (CancellationToken.None);
}
public T Take (CancellationToken cancellationToken)
{
T item;
TryTake (out item, -1, cancellationToken, true);
return item;
}
public bool TryTake (out T item)
{
return TryTake (out item, 0, CancellationToken.None);
}
public bool TryTake (out T item, int millisecondsTimeout, CancellationToken cancellationToken)
{
return TryTake (out item, millisecondsTimeout, cancellationToken, false);
}
bool TryTake (out T item, int milliseconds, CancellationToken cancellationToken, bool throwComplete)
{
if (milliseconds < -1)
throw new ArgumentOutOfRangeException ("milliseconds");
item = default (T);
SpinWait sw = new SpinWait ();
long start = milliseconds == -1 ? 0 : watch.ElapsedMilliseconds;
do {
cancellationToken.ThrowIfCancellationRequested ();
int cachedRemoveId = removeId;
int cachedAddId = addId;
// Empty case
if (cachedRemoveId == cachedAddId) {
if (milliseconds == 0)
return false;
if (IsCompleted) {
if (throwComplete)
ThrowCompleteException ();
else
return false;
}
if (sw.Count <= spinCount) {
sw.SpinOnce ();
} else {
mreAdd.Reset ();
if (cachedRemoveId != removeId || cachedAddId != addId) {
mreAdd.Set ();
continue;
}
mreAdd.Wait (ComputeTimeout (milliseconds, start), cancellationToken);
}
continue;
}
if (Interlocked.CompareExchange (ref removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
continue;
while (!underlyingColl.TryTake (out item));
mreRemove.Set ();
return true;
} while (milliseconds == -1 || (watch.ElapsedMilliseconds - start) < milliseconds);
return false;
}
public bool TryTake (out T item, TimeSpan timeout)
{
return TryTake (out item, (int)timeout.TotalMilliseconds);
}
public bool TryTake (out T item, int millisecondsTimeout)
{
item = default (T);
return TryTake (out item, millisecondsTimeout, CancellationToken.None, false);
}
static int ComputeTimeout (int millisecondsTimeout, long start)
{
return millisecondsTimeout == -1 ? 500 : (int)Math.Max (watch.ElapsedMilliseconds - start - millisecondsTimeout, 1);
}
#endregion
#region static methods
static void CheckArray (BlockingCollection<T>[] collections)
{
if (collections == null)
throw new ArgumentNullException ("collections");
if (collections.Length == 0 || IsThereANullElement (collections))
throw new ArgumentException ("The collections argument is a 0-length array or contains a null element.", "collections");
}
static bool IsThereANullElement (BlockingCollection<T>[] collections)
{
foreach (BlockingCollection<T> e in collections)
if (e == null)
return true;
return false;
}
public static int AddToAny (BlockingCollection<T>[] collections, T item)
{
return AddToAny (collections, item, CancellationToken.None);
}
public static int AddToAny (BlockingCollection<T>[] collections, T item, CancellationToken cancellationToken)
{
CheckArray (collections);
WaitHandle[] wait_table = null;
while (true) {
for (int i = 0; i < collections.Length; ++i) {
if (collections [i].TryAdd (item))
return i;
}
cancellationToken.ThrowIfCancellationRequested ();
if (wait_table == null) {
wait_table = new WaitHandle [collections.Length + 1];
for (int i = 0; i < collections.Length; ++i)
wait_table [i] = collections [i].mreAdd.WaitHandle;
wait_table [collections.Length] = cancellationToken.WaitHandle;
}
WaitHandle.WaitAny (wait_table);
cancellationToken.ThrowIfCancellationRequested ();
}
}
public static int TryAddToAny (BlockingCollection<T>[] collections, T item)
{
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryAdd (item))
return index;
index++;
}
return -1;
}
public static int TryAddToAny (BlockingCollection<T>[] collections, T item, TimeSpan timeout)
{
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryAdd (item, timeout))
return index;
index++;
}
return -1;
}
public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout)
{
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryAdd (item, millisecondsTimeout))
return index;
index++;
}
return -1;
}
public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout,
CancellationToken cancellationToken)
{
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryAdd (item, millisecondsTimeout, cancellationToken))
return index;
index++;
}
return -1;
}
public static int TakeFromAny (BlockingCollection<T>[] collections, out T item)
{
return TakeFromAny (collections, out item, CancellationToken.None);
}
public static int TakeFromAny (BlockingCollection<T>[] collections, out T item, CancellationToken cancellationToken)
{
item = default (T);
CheckArray (collections);
WaitHandle[] wait_table = null;
while (true) {
for (int i = 0; i < collections.Length; ++i) {
if (collections [i].TryTake (out item))
return i;
}
cancellationToken.ThrowIfCancellationRequested ();
if (wait_table == null) {
wait_table = new WaitHandle [collections.Length + 1];
for (int i = 0; i < collections.Length; ++i)
wait_table [i] = collections [i].mreRemove.WaitHandle;
wait_table [collections.Length] = cancellationToken.WaitHandle;
}
WaitHandle.WaitAny (wait_table);
cancellationToken.ThrowIfCancellationRequested ();
}
}
public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item)
{
item = default (T);
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryTake (out item))
return index;
index++;
}
return -1;
}
public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, TimeSpan timeout)
{
item = default (T);
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryTake (out item, timeout))
return index;
index++;
}
return -1;
}
public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout)
{
item = default (T);
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryTake (out item, millisecondsTimeout))
return index;
index++;
}
return -1;
}
public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout,
CancellationToken cancellationToken)
{
item = default (T);
CheckArray (collections);
int index = 0;
foreach (var coll in collections) {
if (coll.TryTake (out item, millisecondsTimeout, cancellationToken))
return index;
index++;
}
return -1;
}
#endregion
public void CompleteAdding ()
{
// No further add beside that point
completeId = addId;
isComplete.Value = true;
// Wakeup some operation in case this has an impact
mreAdd.Set ();
mreRemove.Set ();
}
void ThrowCompleteException ()
{
throw new InvalidOperationException ("The BlockingCollection<T> has"
+ " been marked as complete with regards to additions.");
}
void ICollection.CopyTo (Array array, int index)
{
underlyingColl.CopyTo (array, index);
}
public void CopyTo (T[] array, int index)
{
underlyingColl.CopyTo (array, index);
}
public IEnumerable<T> GetConsumingEnumerable ()
{
return GetConsumingEnumerable (CancellationToken.None);
}
public IEnumerable<T> GetConsumingEnumerable (CancellationToken cancellationToken)
{
while (true) {
T item = default (T);
try {
item = Take (cancellationToken);
} catch {
// Then the exception is perfectly normal
if (IsCompleted)
break;
// otherwise rethrow
throw;
}
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return ((IEnumerable)underlyingColl).GetEnumerator ();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator ()
{
return ((IEnumerable<T>)underlyingColl).GetEnumerator ();
}
public void Dispose ()
{
}
protected virtual void Dispose (bool disposing)
{
}
public T[] ToArray ()
{
return underlyingColl.ToArray ();
}
public int BoundedCapacity {
get {
return upperBound;
}
}
public int Count {
get {
return underlyingColl.Count;
}
}
public bool IsAddingCompleted {
get {
return isComplete.Value;
}
}
public bool IsCompleted {
get {
return isComplete.Value && addId == removeId;
}
}
object ICollection.SyncRoot {
get {
return underlyingColl.SyncRoot;
}
}
bool ICollection.IsSynchronized {
get {
return underlyingColl.IsSynchronized;
}
}
}
}
#endif
|