我已经阅读过以前的关于ConcurrentBag
的问题,但没有在多线程中找到实际的实现示例。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
中的物品就够了?
我认为在这种情况下开销和整体性能会比使用同步方法更大。你测过它了吗? – 2013-03-20 10:58:58
ConcurrentBag有一个构造函数,它需要一个'IEnumerable''var myBag = new ConcurrentBag (products);' –
Romoku
2013-03-20 11:55:44
嗨llya,我的意思是我仍然使用上面几乎相同的代码,除了我将替换ConcurrentBag与一个列表并添加一个锁,当在Parallel.ForEach内列表中添加一个产品 –
hisoka21
2013-03-20 13:28:27