Skip to content
Tutorials Center
My learning

Topics

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).

C#
using System.Collections.Concurrent;

var queue = new ConcurrentQueue<int>();
queue.Enqueue(1);
if (queue.TryDequeue(out int item))
{
    Console.WriteLine(item);
}

Try it

C# Many threads, one queue

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.

C# Stack, bag and Try methods

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

C#
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 single Try... call and check its result.
  • Count is a snapshot. On a queue or stack it is accurate at that instant but may be stale a moment later; use IsEmpty instead of Count == 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.Collections synchronized wrappers (ArrayList.Synchronized) in new code.