C# Reference ยท Collections
Concurrent collections
Reference for System.Collections.Concurrent: ConcurrentQueue, ConcurrentStack, ConcurrentBag, ConcurrentDictionary, thread safety guarantees and pitfalls.
The System.Collections.Concurrent namespace contains collections that several threads can read and write at the same time without you adding a lock. They use fine-grained locking or lock-free algorithms internally, so they scale better than wrapping a normal collection in one big lock when many threads compete.
The main types are ConcurrentQueue<T> (FIFO), ConcurrentStack<T> (LIFO), ConcurrentBag<T> (unordered, fast when each thread mostly takes its own items) and ConcurrentDictionary<TKey,TValue>. BlockingCollection<T> adds waiting and bounds on top of them (see BlockingCollection and Channels).
using System.Collections.Concurrent; var queue = new ConcurrentQueue<int>(); queue.Enqueue(1); if (queue.TryDequeue(out int item)) { Console.WriteLine(item); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class ConcurrentQueue<T> { public void Enqueue(T item); public bool TryDequeue(out T result); public bool TryPeek(out T result); public bool IsEmpty { get; } public int Count { get; } } public class ConcurrentStack<T> { public void Push(T item); public void PushRange(T[] items); public bool TryPop(out T result); public bool TryPeek(out T result); } public class ConcurrentBag<T> { public void Add(T item); public bool TryTake(out T result); public bool TryPeek(out T result); }
| Type | Order | Best for |
|---|---|---|
ConcurrentQueue<T> |
FIFO | Work queues, pipelines |
ConcurrentStack<T> |
LIFO | Undo-like or scratch stacks |
ConcurrentBag<T> |
None | Pools where each thread mostly reuses its own items |
ConcurrentDictionary<K,V> |
Keyed | Shared caches and counters |
Returns: the Try... methods return true on success and false when the collection is empty (the out value is then the default). There is no throwing Dequeue.
Errors: none for empty collections. ArgumentNullException for a null array in PushRange.
Usage notes
- Each call is atomic, sequences of calls are not.
if (!queue.IsEmpty) queue.TryDequeue(...)can still fail, because another thread may take the item in between. Always use the singleTry...call and check its result. Countis a snapshot. On a queue or stack it is accurate at that instant but may be stale a moment later; useIsEmptyinstead ofCount == 0, which is cheaper on stacks and bags.- Enumeration is a moment-in-time snapshot for queue, stack and bag, so it never throws "collection was modified", unlike
List<T>. - Choose the type by access pattern. A bag has no ordering, which is why it is fast; do not use it if order matters. For a plain producer-consumer pipeline, a
Channel<T>is usually the best modern choice. - Not a replacement for a lock around invariants. Two collections that must stay consistent with each other still need a shared
lock. - Memory: lock-free queues allocate segments; high churn creates garbage, but far less than lock contention costs.
- Do not use the non-generic
System.Collectionssynchronized wrappers (ArrayList.Synchronized) in new code.