Is Parallel.ForEach in ConcurrentBag thread saf

2020-07-03 07:52发布

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.

2条回答
爷的心禁止访问
2楼-- · 2020-07-03 08:34

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 a List<T> when you're done.

查看更多
Summer. ? 凉城
3楼-- · 2020-07-03 08:43

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.

查看更多
登录 后发表回答