在ConcurrentBag T中是并行的。线程安全 [英] Is Parallel.ForEach in ConcurrentBag<T> thread safe

查看:181
本文介绍了在ConcurrentBag T中是并行的。线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN上对ConcurrentBag的描述不清楚:

Description of ConcurrentBag on MSDN is not clear:

当订购无关紧要时,袋子可用于存储对象,并且与集合不同,袋子支持重复。 ConcurrentBag是一种线程安全的bag实现,针对同一线程将同时产生和使用存储在bag中的数据的场景进行了优化。

我的问题是它是线程安全的,如果在Parallel.ForEach中使用ConcurrentBag是一个好习惯。

My question is it thread safe and if this is a good practice to use ConcurrentBag in Parallel.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中使用常规列表使用同步锁定。

This way I don't have to use synchronization locking in Parallel.ForEach using regular List.

非常感谢。 / p>

Thanks a lot.

推荐答案

这对我来说很好。您使用它的方式是线程安全的。

That looks fine to me. The way you're using it is thread-safe.

如果您可以返回 IEnumerable< XYZ> ,则可以通过不复制到 List< T>来提高效率。 ; 完成后。

If you could return an IEnumerable<XYZ>, it could be made more efficient by not copying to a List<T> when you're done.

这篇关于在ConcurrentBag T中是并行的。线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆