ConcurrentBag(中的​​MyType)VS目录(中的MyType)目录、ConcurrentBag、MyType、VS

2023-09-03 10:21:00 作者:最强笨蛋

什么是使用ConcurrentBag(中的​​MyType)对只使用一个列表(中的MyType)的优势在哪里? 在CB的MSDN页面(http://msdn.microsoft.com/en-us/library/dd381779(v=VS.100).aspx)指出,

What is the advantage of using a ConcurrentBag(Of MyType) against just using a List(Of MyType)? The MSDN page on the CB (http://msdn.microsoft.com/en-us/library/dd381779(v=VS.100).aspx) states that

ConcurrentBag(叔)是线程安全的   袋的实施,优化了   场景同一线程将   既生产和消费数据   储存于袋中

ConcurrentBag(Of T) is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag

那么,什么是优势?我可以理解,在并发命名空间中的其他集合类型的优势,但是这一个我无法理解。

So what is the advantage? I can understand the advantage of the other collection types in the Concurrency namespace, but this one puzzled me.

感谢。

推荐答案

在内部,ConcurrentBag是用几种不同的解释,每个编写线程执行。

Internally, the ConcurrentBag is implemented using several different Lists, one for each writing thread.

你有什么办法引用这种说法是,从包里读取数据时,会优先考虑该线程创建的列表。意思是,它会首先检查列表中的线程在另一个线程的名单冒着争了。

What that statement you quoted means is that, when reading from the bag, it will prioritize the list created for that thread. Meaning, it will first check the list for that thread before risking contention on another thread's list.

这方面,它可以最大限度地减少锁争用当多个线程读取和写入。当读出线程没有列表,或者它的列表是空的,它有锁分配到一个不同的线程列表。但是,如果你有多个线程都读取和写入自己的名单,那么你永远不会有锁争用。

This way it can minimize lock contention when multiple threads are both reading and writing. When the reading thread doesn't have a list, or its list is empty, it has to lock a list assigned to a different thread. But, if you have multiple threads all reading from and writing to their own list, then you won't ever have lock contention.

 
精彩推荐
图片推荐