ConcurrentBag< MyType>与List< MyType> [英] ConcurrentBag<MyType> Vs List<MyType>

查看:92
本文介绍了ConcurrentBag< MyType>与List< MyType>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对于仅使用List(Of MyType),使用ConcurrentBag(Of MyType)有什么优势? CB上的MSDN页面指出

What is the advantage of using a ConcurrentBag(Of MyType) against just using a List(Of MyType)? The MSDN page on the CB states that

ConcurrentBag(Of T)是线程安全的 袋实施,针对以下情况进行了优化 同一线程将 产生和使用数据 放在袋子里

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

那么优势是什么?我可以理解Concurrency命名空间中其他集合类型的优势,但这使我感到困惑.

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.

这篇关于ConcurrentBag< MyType>与List< MyType>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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