简体   繁体   中英

Adding and removing elements of a ConcurrentBag during enumeration

What happens when a thread is adding or removing elements of a ConcurrentBag<T> while another thread is enumerating this bag? Will the new elements also show up in the enumeration and will the removed elements not show up?

One can read the fine manual to discover:

ConcurrentBag<T>.GetEnumerator Method

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 .

Emphasis mine.

Justin Etheredge has a blog post explaining the features of the ConcurrentBag class:

In order to implement the enumerable as thread-safe, the GetEnumerator method returns a moment-in-time snapshot of the ConcurrentBag as it was when you started iterating over it. In this way, any items added after the enumeration started won't be seen while iterating over the data structure.

This means: When starting to enumerate the ConcurrentBag<T> , a snapshot of the current state is created. The enumeration will only show the elements that were present in the bag at the time the enumeration started.

Other threads can still add and remove elements as they like but this will not change the set of elements seen by the enumeration.

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