何时使用 BlockingCollection 以及何时使用 ConcurrentBag 而不是 List<T>? [英] When to use BlockingCollection and when ConcurrentBag instead of List<T>?
问题描述
问题为什么这个 Parallel.ForEach 代码会冻结程序?" 建议替换为列出 WPF 应用程序中 ConcurrentBag 的使用情况.
The accepted answer to question "Why does this Parallel.ForEach code freeze the program up?" advises to substitute the List usage by ConcurrentBag in a WPF application.
我想了解 在这种情况下可以使用 BlockingCollection 代替吗?
推荐答案
你确实可以使用 BlockingCollection
,但这样做绝对没有意义.
You can indeed use a BlockingCollection
, but there is absolutely no point in doing so.
首先,请注意 BlockingCollection
是实现 IProducerConsumerCollection
.任何实现该接口的类型都可以用作底层存储:
First off, note that BlockingCollection
is a wrapper around a collection that implements IProducerConsumerCollection<T>
. Any type that implements that interface can be used as the underlying storage:
当你创建一个 BlockingCollection
对象时,你可以指定不不仅是有限容量,还有要使用的集合类型.为了例如,您可以为 first in 指定一个 ConcurrentQueue
对象,先出 (FIFO) 行为,或 ConcurrentStack
对象用于最后进先出 (LIFO) 行为.您可以使用任何集合类实现 IProducerConsumerCollection
接口.默认的BlockingCollection
的集合类型是 ConcurrentQueue
.
When you create a
BlockingCollection<T>
object, you can specify not only the bounded capacity but also the type of collection to use. For example, you could specify aConcurrentQueue<T>
object for first in, first out (FIFO) behavior, or aConcurrentStack<T>
object for last in,first out (LIFO) behavior. You can use any collection class that implements theIProducerConsumerCollection<T>
interface. The default collection type forBlockingCollection<T>
isConcurrentQueue<T>
.
这包括 ConcurrentBag
,这意味着您可以有一个阻塞并发包.那么普通的 IProducerConsumerCollection
和阻塞的集合有什么区别呢?BlockingCollection
的文档说(强调我的):
This includes ConcurrentBag<T>
, which means you can have a blocking concurrent bag. So what's the difference between a plain IProducerConsumerCollection<T>
and a blocking collection? The documentation of BlockingCollection
says (emphasis mine):
BlockingCollection
用作IProducerConsumerCollection
实例,允许删除尝试从集合中阻止,直到数据可以被删除.类似地,可以创建 BlockingCollection
来强制执行中允许的数据元素数量的上限IProducerConsumerCollection
[...]
BlockingCollection<T>
is used as a wrapper for anIProducerConsumerCollection<T>
instance, allowing removal attempts from the collection to block until data is available to be removed. Similarly, aBlockingCollection<T>
can be created to enforce an upper-bound on the number of data elements allowed in theIProducerConsumerCollection<T>
[...]
由于在链接的问题中不需要做这些事情中的任何一件,使用 BlockingCollection
只需添加一层未使用的功能.
Since in the linked question there is no need to do either of these things, using BlockingCollection
simply adds a layer of functionality that goes unused.
这篇关于何时使用 BlockingCollection 以及何时使用 ConcurrentBag 而不是 List<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!