gpt4 book ai didi

c# - ConcurrentBag 的正确用法是什么?

转载 作者:IT王子 更新时间:2023-10-29 03:51:19 25 4
gpt4 key购买 nike

我已经在这里阅读了之前关于 ConcurrentBag 的问题但没有找到在多线程中的实际实现示例。

ConcurrentBag is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag."

目前这是我代码中的当前用法(这是简化的而非实际代码):

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 的正确使用。线程局部变量是包的成员,并且在包存在的同时将有资格进行垃圾收集(清除内容不会释放它们)。你是对的,一个带锁的简单 List 就足以满足你的情况。如果您在循环中所做的工作非常重要,则线程同步的类型对整体性能影响不大。在这种情况下,您可能更愿意使用自己熟悉的内容。

另一种选择是使用 ParallelEnumerable.Select ,这与您要更紧密地尝试做的事情相匹配。同样,您将看到的任何性能差异都可以忽略不计,坚持您所知道的并没有错。

一如既往,如果它的性能很关键,那么尝试和测量是无可替代的。

关于c# - ConcurrentBag 的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15521584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com