【发布时间】:2013-03-09 10:21:26
【问题描述】:
我已经在这里阅读过关于ConcurrentBag 的先前问题,但没有找到多线程实现的实际示例。
ConcurrentBag 是一种线程安全的包实现,针对同一线程将同时生产和使用包中存储的数据的场景进行了优化。”
目前这是我代码中的当前用法(这是简化而不是实际代码):
private void MyMethod()
{
List<Product> products = GetAllProducts(); // Get list of products
ConcurrentBag<Product> myBag = new ConcurrentBag<Product>();
//products were simply added here in the ConcurrentBag to simplify the code
//actual code process each product before adding in the bag
Parallel.ForEach(
products,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
product => myBag.Add(product));
ProcessBag(myBag); // method to process each items in the concurrentbag
}
我的问题:
这是ConcurrentBag 的正确用法吗?这种场景可以用ConcurrentBag吗?
对我来说,我认为简单的List<Product> 和手动锁定会更好。原因是上面的场景已经打破了“同一个线程将同时生产和消费存储在包中的数据”规则。
另外我还发现,在每个线程中并行创建的ThreadLocal存储在操作后仍然存在(即使线程被重用是这样吗?),这可能会导致不希望的内存泄漏。
我在这个人中是对的吗?或者一个简单的清除或清空方法来删除ConcurrentBag 中的项目就足够了?
【问题讨论】:
-
我认为在这种情况下,开销和整体性能会比使用同步方法更大。你量过吗?
-
ConcurrentBag 有一个构造函数,它接受
IEnumerable<T>var myBag = new ConcurrentBag<Product>(products); -
你好,我的意思是我仍然会使用上面几乎相同的代码,除了我将用 List
替换 ConcurrentBag 并在添加产品时添加一个锁在 Parallel.ForEach 内的 List 中 -
因为您没有使用相同的线程来添加到包中,因为您将使用 ConcurrentQueue 而不是 ConcurrentBag 获得更好的性能。
标签: c# multithreading concurrency