Search code examples
c#multithreadingforeachparallel-processingparallel.foreach

ConcurrentBag and foreach


I've seen ConcurrentBag and Parallel.ForEach being used in another question. Now I'm wondering if it is still thread safe if I use a regular foreach instead of Parallel.ForEach to read data from a ConcurrentBag.

Thus even though other threads are adding data to and removing data from a ConcurrentBag, I want in a specific thread to go through all items in the bag (it can even be a snapshot of that bag as it doesn't have to be 100% up-to-date) and use the data found for something else.

So my question is, is a normal foreach here doable without breaking the thread safety of the ConcurrentBag or do I HAVE to use Parallel.ForEach?


Solution

  • For your scenario, whether you're evaluating a collection with foreach or Parallel.ForEach makes no difference. This is true of a lot of things. Parallel.ForEach doesn't magically kick enumerators into some special thread-safe mode.

    From the fine manual:

    Remarks

    The enumeration represents a moment-in-time snapshot of the contents of the bag. It does not reflect any updates to the collection after GetEnumerator was called. The enumerator is safe to use concurrently with reads from and writes to the bag.