liveBook · Manning

ConcurrentBag<T>

As explained in C# Concurrency: Asynchronous and multithreaded programming

A .NET thread-safe unordered collection optimized for concurrent additions and removals, especially when the same thread performs both operations.

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

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains Add, TryTake, per-thread queues, and work stealing, but does not provide a complete implementation or benchmark.
Examples
Uses a BlockingCollection<T>-based work queue whose handlers both consume and add items.
What you can do after
Apply it when unordered access and same-thread producer-consumer behavior make local queues more valuable than ordering.
How it connects
Connects ConcurrentBag<T> with BlockingCollection<T>, concurrent collections, work stealing, and thread synchronization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.