我已经在这里阅读过以前的问题,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
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
这是正确的用法ConcurrentBag
吗?ConcurrentBag
在这种情况下可以使用吗?
对我来说,我认为一个简单List<Product>
的手动锁会做得更好.这样做的原因是上面的场景已经打破了" 同一个线程将生成和消费存储在包中的数据 "规则.
另外我还发现 …