ConcurrentBag中是 Parallel.ForEach线程安全
MSDN 上对 ConcurrentBag 的描述不清楚:
当顺序不重要时,包对于存储对象很有用,并且与集合不同,包支持重复。 ConcurrentBag 是一个线程安全的包实现,针对同一线程同时生成和使用存储在包中的数据的场景进行了优化。
我的问题是它是线程安全的,以及这是否是并行使用 ConcurrentBag 的良好实践.ForEach。
例如:
private List<XYZ> MyMethod(List<MyData> myData)
{
var data = new ConcurrentBag<XYZ>();
Parallel.ForEach(myData, item =>
{
// Some data manipulation
data.Add(new XYZ(/* constructor parameters */);
});
return data.ToList();
}
这样我就不必使用常规列表在 Parallel.ForEach 中使用同步锁定。
多谢。
Description of ConcurrentBag on MSDN is not clear:
Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support duplicates. 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.
My question is it thread safe and if this is a good practice to use ConcurrentBag in Parallel.ForEach.
For Instance:
private List<XYZ> MyMethod(List<MyData> myData)
{
var data = new ConcurrentBag<XYZ>();
Parallel.ForEach(myData, item =>
{
// Some data manipulation
data.Add(new XYZ(/* constructor parameters */);
});
return data.ToList();
}
This way I don't have to use synchronization locking in Parallel.ForEach using regular List.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对我来说看起来不错。您使用它的方式是线程安全的。
如果您可以返回
IEnumerable
,则在完成后不复制到List
可以提高效率。That looks fine to me. The way you're using it is thread-safe.
If you could return an
IEnumerable<XYZ>
, it could be made more efficient by not copying to aList<T>
when you're done.ConcurrentBag 和 Parallel.ForEach 在我看来没有问题。如果您在具有大量多用户访问的场景中使用此类型,则实现中的这些类可能会将 cpu 进程提升到可能导致 Web 服务器崩溃的水平。此外,该实现启动 N 个任务(线程)来执行每一次迭代,因此在选择此类和实现时要小心。我最近遇到了这种情况,我必须提取内存转储来分析我的 Web 应用程序核心发生了什么。所以,要小心,因为 Concurrentbag 是 ThreadSafe 的,在 Web 场景中这不是更好的方法。
ConcurrentBag and Parallel.ForEach seems to me, no problem. If you uses this types in scenarios that has a large volume multi-user access, these classes in your implementation could rise up cpu process to levels that can crash your web-server. Furthermore, this implementation starts N tasks (threads) to execute each one of iterations, so be careful when choice this classes ans implementations. I recently spent in this situation and I had to extract memory dump to analyze whats happens into my web application core. So, be careful 'cause Concurrentbag is ThreadSafe and in web scenarios it is no better way.