ConcurrentBag<T> is a thread-safe, unordered collection for concurrent additions and removals. Add inserts items, while TryTake retrieves and removes them; duplicate items are allowed. section 13.2.5 section 13.5
Its implementation maintains per-thread queues. TryTake first seeks an item inserted by the current thread, avoiding blocking; if necessary, it steals work from another thread’s queue, which requires synchronization and is slower. section 13.2.5
Choose ConcurrentBag<T> when:
- Item order does not matter. section 13.2.5
- The same thread, or the same set of threads, both adds and retrieves items. section 13.2.5
- Avoid it for asynchronous workflows when execution may resume on different threads. section 13.2.5
Specialized work-queue backing collection
A BlockingCollection<T>-based work queue can use ConcurrentBag<T> when item handlers also add items to the bag. This is uncommon: ConcurrentQueue<T> is the usual backing collection, while ConcurrentBag<T> specifically favors same-thread reads and writes. section 13.2.2 section 13.2.5
