Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Parallel.ForEach in ConcurrentBag<T> thread safe

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.

like image 784
Vlad Bezden Avatar asked Jul 08 '11 20:07

Vlad Bezden


1 Answers

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.

like image 166
Stephen Cleary Avatar answered Oct 04 '22 19:10

Stephen Cleary