Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like asynchronous BlockingCollection<T>?

I would like to await on the result of BlockingCollection<T>.Take() asynchronously, so I do not block the thread. Looking for anything like this:

var item = await blockingCollection.TakeAsync(); 

I know I could do this:

var item = await Task.Run(() => blockingCollection.Take()); 

but that kinda kills the whole idea, because another thread (of ThreadPool) gets blocked instead.

Is there any alternative?

like image 357
avo Avatar asked Jan 20 '14 02:01

avo


People also ask

How does Blocking collection work?

BlockingCollection<T> provides a GetConsumingEnumerable method that enables consumers to use foreach ( For Each in Visual Basic) to remove items until the collection is completed, which means it is empty and no more items will be added.

What is Blocking queue in c#?

If the queue reaches a specific size all threads that are filling the queue will be blocked on add until an item is removed from the queue.


1 Answers

There are four alternatives that I know of.

The first is Channels, which provides a threadsafe queue that supports asynchronous Read and Write operations. Channels are highly optimized and optionally support dropping some items if a threshold is reached.

The next is BufferBlock<T> from TPL Dataflow. If you only have a single consumer, you can use OutputAvailableAsync or ReceiveAsync, or just link it to an ActionBlock<T>. For more information, see my blog.

The last two are types that I created, available in my AsyncEx library.

AsyncCollection<T> is the async near-equivalent of BlockingCollection<T>, capable of wrapping a concurrent producer/consumer collection such as ConcurrentQueue<T> or ConcurrentBag<T>. You can use TakeAsync to asynchronously consume items from the collection. For more information, see my blog.

AsyncProducerConsumerQueue<T> is a more portable async-compatible producer/consumer queue. You can use DequeueAsync to asynchronously consume items from the queue. For more information, see my blog.

The last three of these alternatives allow synchronous and asynchronous puts and takes.

like image 150
Stephen Cleary Avatar answered Sep 22 '22 15:09

Stephen Cleary