Chris
Chris

Reputation: 7184

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?

Upvotes: 4

Views: 3597

Answers (2)

ta.speot.is
ta.speot.is

Reputation: 27214

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.

Upvotes: 8

Chris
Chris

Reputation: 7184

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.

Upvotes: 1

Related Questions