private static async Task RunConsumerAsync(IAsyncCollection <int> queue, IntHolder itemsTakeHolder, int itemsAddedTotal, CancellationTokenSource cancelSource) { try { CancellationToken cancelToken = cancelSource.Token; while (true) { int item = await queue.TakeAsync(cancelToken).ConfigureAwait(false); int itemsTakenLocal = Interlocked.Increment(ref itemsTakeHolder.Value); if (itemsTakenLocal >= itemsAddedTotal) { cancelSource.Cancel(); } } } catch (OperationCanceledException) { } }
/// <summary> /// Removes and returns an item from the collection in an asynchronous manner. /// </summary> public static Task <T> TakeAsync <T>(this IAsyncCollection <T> collection) { return(collection.TakeAsync(CancellationToken.None)); }