BlockingCollection的目的是什么(叔) [英] What is the purpose of BlockingCollection(Of T)

查看:802
本文介绍了BlockingCollection的目的是什么(叔)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm试图了解BlockingCollection在新的并行堆栈的上下文中,目的在.NET 4。

I´m trying to understand the purpose of BlockingCollection in the context of the new Parallel Stacks on .NET 4.

借助 MSDN 的文件说:

BlockingCollection用作包装一个IProducerConsumerCollection例如,允许从收集除去了试图阻止直到数据可被去除。同样,一个BlockingCollection可以创建执行的上界上在IProducerConsumerCollection允许的数据元素的数量;然后除了试图收集可能阻塞,直到有可用空间来存储添加的条目。

BlockingCollection is used as a wrapper for an IProducerConsumerCollection instance, allowing removal attempts from the collection to block until data is available to be removed. Similarly, a BlockingCollection can be created to enforce an upper-bound on the number of data elements allowed in the IProducerConsumerCollection; addition attempts to the collection may then block until space is available to store the added items.

然而,当我看一些IProducerConsumerCollection的实施,像ConcurrentQueue我看到,他们提供了一个免费的锁,线程安全的,实现。那么,为什么需要一个BlockingCollection提供了锁定机制?在通过BlockingCollection包装使用这些藏品的MSDN显示所有的例子,什么是直接使用这些藏品的烦恼?怎样才能产生使用BlockingCollection好处?

However when I look at the implementation of some IProducerConsumerCollection, like ConcurrentQueue I see that they provide a lock free, thread safe, implementations. So why is needed the lock mechanism that BlockingCollection provides? All the examples in the msdn show using those collections via BlockingCollection wrapper, what are the troubles of using those collections directly? What benefit produces using BlockingCollection?

推荐答案

阻塞,直到可以执行的操作是方便,如果你有没有别的工作要做。(或者更确切地说:无法进行,直到操作已执行)

Blocking until the operation can be performed is a convenience if you have nothing else to do anyway (or rather: cannot proceed until the operation has been performed).

如果你从要读取数据非阻塞队列,并有目前没有数据,你必须定期轮询,或者等待一些信号,直到有数据。如果队列块,即已经自动完成的。

If you have a non-blocking queue from which you want to read data, and there is no data at the moment, you have to periodically poll it, or wait on some semaphore, until there is data. If the queue blocks, that is already done automatically.

同样,如果您尝试添加到非阻塞队列已满,该操作将只是失败,那么你必须弄清楚该怎么做。阻塞队列只会等到有空间。

Similarly, if you try to add to a non-blocking queue that is full, the operation will just fail, and then you have to figure out what to do. The blocking queue will just wait until there is space.

如果你有一些聪明的做的等待(如检查另一个数据队列,或提出一个QueueTooFullException),而不是那么您需要的非阻塞队列,但往往事实并非如此。

If you have something clever to do instead of waiting (such as checking another queue for data, or raising a QueueTooFullException) then you want the non-blocking queue, but often that is not the case.

通常,有一种方法对阻塞队列指定一个超时。

Often, there is a way to specify a timeout on blocking queues.

这篇关于BlockingCollection的目的是什么(叔)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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