In .NET, how do ConcurrentQueue<T>, ConcurrentStack<T> and ConcurrentBag<T> differ, and when is ConcurrentBag<T> the right choice?
answer
- FIFO, LIFO, unordered
- Try methods return false
- a list per thread
- steal only when your own is empty
basics
~20 sConcurrentQueue<T> is first-in first-out and ConcurrentStack<T> last-in first-out. ConcurrentBag<T> promises no order: each thread keeps its own list and steals from others only when that is empty, so it pays off when the same threads both add and take.
solid answer
~50 sAll three implement `IProducerConsumerCollection<T>` and offer `TryDequeue`, `TryPop` and `TryTake`, which return `false` on an empty collection instead of throwing. `ConcurrentQueue<T>` is a linked list of ring-buffer segments updated mostly with `Interlocked` operations: first-in first-out with few allocations. `ConcurrentStack<T>` allocates a node per `Push`, swaps its head with compare-and-swap, adds `PushRange`/`TryPopRange` for batches, and its `Count` walks the whole list. `ConcurrentBag<T>` is documented as unordered and optimised for threads that both produce and consume: each thread adds to its own work-stealing queue held in a `ThreadLocal`, takes from it first, and steals from another thread's queue only when its own is empty. That makes it fast for an object pool shared by workers and slower than a queue when some threads only produce and others only consume. For all three, prefer `IsEmpty` to `Count == 0`.
code
csharp · 17 linesusing System.Collections.Concurrent;
var queue = new ConcurrentQueue<int>([1, 2, 3]);
var stack = new ConcurrentStack<int>([1, 2, 3]);
var bag = new ConcurrentBag<int>();
foreach (int n in new[] { 1, 2, 3 }) bag.Add(n);
queue.TryDequeue(out int q);
stack.TryPop(out int s);
bag.TryTake(out int b); // the thread that added the items
Console.WriteLine($"queue {q}, stack {s}, bag (same thread) {b}");
int stolen = 0;
var other = new Thread(() => bag.TryTake(out stolen)); // a thread with no items of its own
other.Start();
other.Join();
Console.WriteLine($"bag (other thread) {stolen}");go deeper
Match the type to the order you need: queue for first-in first-out, stack for last-in first-out, and know that the Try methods return false when empty.
Explain the bag's per-thread queues and stealing, why that suits threads that add and take, and why IsEmpty beats Count on these types.
Choose by workload: spot a ConcurrentBag<T> in a producer–consumer pipeline, a ConcurrentStack<T>.Count on a hot path, or an IsEmpty-then-take pattern, and explain the cost of each.
Ask whether a collection is the right hand-off at all: if consumers need to wait or producers need back-pressure, a blocking or channel-based design fits better than polling a concurrent collection.
## Three shapes behind one interface `System.Collections.Concurrent` has three unbounded collections for passing items between threads. All three implement `IProducerConsumerCollection<T>` (whose `TryAdd` and `TryTake` let `BlockingCollection<T>` wrap any of them) and `IReadOnlyCollection<T>`. Unlike `Queue<T>.Dequeue` or `Stack<T>.Pop`, which throw `InvalidOperationException` on an empty collection, their take methods are **Try methods**: they return `false` and set the out value to `default`. | | `ConcurrentQueue<T>` | `ConcurrentStack<T>` | `ConcurrentBag<T>` | |---|---|---|---| | Order | first in, first out | last in, first out | none documented | | Add / take | `Enqueue` / `TryDequeue` | `Push` / `TryPop` | `Add` / `TryTake` | | Storage | linked ring-buffer segments | one node object per item | one work-stealing queue per thread | | `Count` | computed from segment indexes | walks every node, O(n) | freezes the bag: takes every lock | | Best fit | producers hand work to consumers | most-recent-first reuse | threads that both add and take | ## ConcurrentQueue<T> The queue is a linked list of fixed-size ring buffers (segments). `Enqueue` and `TryDequeue` claim slots with `Interlocked` operations, so as long as the current segment has room no allocation happens. A private lock is taken only for rarer work: linking a new segment when one fills, or freezing segments for a snapshot. The .NET docs say the queue and stack use no locks at all; the .NET 10 source shows this cross-segment lock, so read "no locks on the common path". Use `IsEmpty` rather than `Count == 0`: the source comments recommend it, and `IsEmpty` is a cheap peek. `TryPeek(out T)` reads the head item without removing it, and is just as stale as `IsEmpty` by the time you act on it. ## ConcurrentStack<T> The stack is a singly linked list. `Push` allocates a node and swaps it in as the new head with `Interlocked.CompareExchange`, retrying on contention; `TryPop` swaps the head out the same way. Points worth knowing: - **`PushRange(T[])` and `TryPopRange(T[])`** move many items with one swap, which the docs say can greatly speed up access. - **`Count` is O(n):** the source comment says it walks the list, so it is a poor thing to call on every operation. `IsEmpty` just checks whether the head is null. - **Every push allocates,** unlike the queue's reused segments. ## ConcurrentBag<T> The bag's class comment says it is "optimized for scenarios where the same thread will be both producing and consuming data stored in the bag". The design explains why: 1. Each thread that adds gets its own **work-stealing queue**, found through a `ThreadLocal`. 2. `Add` pushes onto the calling thread's own queue, normally without contention. 3. `TryTake` pops from the calling thread's own queue first, from the end it last added to. 4. Only when that queue is empty does it **steal** from the other end of another thread's queue, under that queue's lock. 5. `Count`, `ToArray`, enumeration, and `IsEmpty` when the calling thread's own queue is empty **freeze** the bag: they take a global lock and every per-thread queue's lock. So the bag shines for an **object pool** used by a fixed set of workers: each worker returns objects and takes them back, mostly from its own queue. In a **pure producer–consumer** split it is the wrong tool: producers' items sit in the producers' queues, consumers own nothing, and every take becomes a steal. The docs say as much: in pure producer–consumer scenarios the bag "will probably perform more slowly than the other concurrent collection types". The order you see in a test is an implementation detail; the type documents none. ## Snapshots and stale answers - Enumerating any of the three gives a **moment-in-time snapshot**, so `foreach` never throws while other threads add or take, and never shows their later changes. - `IsEmpty` and `Count` are stale the moment they return. `if (!queue.IsEmpty) queue.TryDequeue(out var job)` can still fail; just call `TryDequeue` and test its result. ## In the API gateway Request threads that record audit events for a single background writer fit `ConcurrentQueue<T>`: many producers, one consumer, order preserved. A pool of reusable request-signing objects that each worker rents and returns fits `ConcurrentBag<T>`. If the writer should block while the queue is empty, or producers should block while it is full, wrap the queue in `BlockingCollection<T>`.
- Why can ConcurrentBag<T> be slower than ConcurrentQueue<T> in a producer–consumer pipeline?Producers' items land in the producers' own thread-local queues, and consumer threads never add, so they have no queue of their own. Every `TryTake` on a consumer goes down the steal path: it scans other threads' queues and locks the one it takes from. The bag's fast path, a thread taking back what it added, never happens.
- Does enumerating a ConcurrentQueue<T> while other threads enqueue throw?No. `GetEnumerator` takes a moment-in-time snapshot: it freezes the current segments so later enqueues go to new ones. The loop sees exactly the items present when it started and never throws, unlike a `Queue<T>`, whose enumerator throws `InvalidOperationException` once the queue is modified.
- Is IsEmpty followed by TryDequeue a safe way to take one item?It does not break the queue, but the check proves nothing: another consumer can empty the queue between the two calls, so `TryDequeue` can still return `false`. Drop the check, call `TryDequeue` directly and branch on its result, which is the one atomic check-and-take.
Each cashier keeps a personal tray of change and only reaches into a neighbour's tray when their own is empty. That is fast when every cashier both receives and gives change, and slow when some only receive and others only give.
- ConcurrentBag<T> is a thread-safe List<T> that keeps insertion order.
- ConcurrentStack<T>.Count is a cheap field read like Stack<T>.Count.
- Checking IsEmpty before TryDequeue guarantees the dequeue succeeds.
- ConcurrentBag<T> is the fastest choice for any producer–consumer queue.
- TryDequeue throws InvalidOperationException when the queue is empty.