Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and removing elements of a ConcurrentBag during enumeration

Tags:

c#

concurrency

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?

like image 460
Chris Avatar asked Aug 31 '25 17:08

Chris


2 Answers

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.

like image 98
ta.speot.is Avatar answered Sep 02 '25 21:09

ta.speot.is


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.

like image 44
Chris Avatar answered Sep 02 '25 22:09

Chris