我已经在这里阅读了以前的问题,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
就足够了?