private static void RunProducer(IAsyncBatchCollection <int> queue) { for (int i = 0; i < _itemsAddedPerThread; i++) { int item = 42; queue.Add(item); } queue.Flush(); }
private void DdosQueue(IAsyncBatchCollection <int> queue) { int itemsAddedTotal = ProducerTasks * _itemsAddedPerThread; IntHolder itemsTakenHolder = new IntHolder() { Value = 0 }; CancellationTokenSource consumerCancelSource = new CancellationTokenSource(); Task[] consumerTasks = Enumerable.Range(0, ConsumerTasks) .Select(_ => Task.Run(() => RunConsumerAsync(queue, itemsTakenHolder, itemsAddedTotal, consumerCancelSource))) .ToArray(); Task[] producerTasks = Enumerable.Range(0, ProducerTasks) .Select(_ => Task.Run(() => RunProducer(queue))) .ToArray(); Task.WaitAll(producerTasks); Task.WaitAll(consumerTasks); }
private static async Task RunConsumerAsync(IAsyncBatchCollection <int> queue, IntHolder itemsTakeHolder, int itemsAddedTotal, CancellationTokenSource cancelSource) { try { CancellationToken cancelToken = cancelSource.Token; while (true) { IReadOnlyList <int> items = await queue.TakeAsync(cancelToken).ConfigureAwait(false); int itemsTakenLocal = Interlocked.Add(ref itemsTakeHolder.Value, items.Count); if (itemsTakenLocal >= itemsAddedTotal) { cancelSource.Cancel(); } } } catch (OperationCanceledException) { } }
public TimerAsyncBatchQueue(IAsyncBatchCollection <T> innerCollection, TimeSpan flushPeriod) { _innerCollection = innerCollection; _flushTimer = new Timer(_ => Flush(), null, flushPeriod, flushPeriod); }
public static TimerAsyncBatchQueue <T> WithFlushEvery <T>(this IAsyncBatchCollection <T> collection, TimeSpan flushPeriod) => new TimerAsyncBatchQueue <T>(collection, flushPeriod);
public static ValueTask <IReadOnlyList <T> > TakeAsync <T>(this IAsyncBatchCollection <T> collection) => collection.TakeAsync(CancellationToken.None);