简体   繁体   中英

ConcurrentBag and foreach

I've seen ConcurrentBag and Parallel.ForEach being used in another question. Now I'm wondering if it is threadsafe still 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 go through all items in the bag (it can be a snapshot even 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 threadsafety of the ConcurrentBag or do I HAVE to use arallel.ForEach ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM