有没有像异步 BlockingCollection<T> 这样的东西? [英] Is there anything like asynchronous BlockingCollection<T>?

查看:25
本文介绍了有没有像异步 BlockingCollection<T> 这样的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想异步await BlockingCollection.Take() 的结果,所以我不阻塞线程.寻找这样的东西:

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();

我知道我可以做到:

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

但这有点扼杀了整个想法,因为另一个线程(ThreadPool)反而被阻塞了.

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

还有其他选择吗?

推荐答案

我知道有四种替代方案.

There are four alternatives that I know of.

第一个是 Channels,它提供了一个支持异步ReadWrite 操作的线程安全队列.频道经过高度优化,并且可以选择支持在达到阈值时丢弃某些项目.

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.

接下来是 BufferBlock 来自 TPL 数据流.如果您只有一个消费者,则可以使用 OutputAvailableAsyncReceiveAsync,或者将其链接到 ActionBlock.如需更多信息,请查看我的博客.

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.

最后两个是我创建的类型,可在我的 AsyncEx 库 中找到.

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

AsyncCollection;async 近等价于 BlockingCollection,能够包装并发生产者/消费者集合,例如 ConcurrentQueue<;T>ConcurrentBag.您可以使用 TakeAsync 异步使用集合中的项目.如需更多信息,查看我的博客.

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; 是一个更便携的 async 兼容的生产者/消费者队列.您可以使用 DequeueAsync 异步使用队列中的项目.如需更多信息,查看我的博客.

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.

这篇关于有没有像异步 BlockingCollection&lt;T&gt; 这样的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆