Adding and removing elements of a ConcurrentBag during enumeration

孤人 提交于 2021-01-28 02:51:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16952400/adding-and-removing-elements-of-a-concurrentbag-during-enumeration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!