Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

Concurrent collections in use

How to use ConcurrentDictionary, ConcurrentQueue, ConcurrentBag and BlockingCollection correctly: atomic updates, GetOrAdd traps, and what is not thread-safe.

The types in System.Collections.Concurrent are safe to call from several threads at once, without an outside lock. But "each method is thread-safe" is not the same as "my code is correct": a check followed by an action is two calls, and another thread can run in between.

This page is about the patterns that make concurrent collections work, and the traps around them. For the full member lists see Concurrent collections, ConcurrentDictionary and BlockingCollection.

C#
var counts = new ConcurrentDictionary<string, int>();
counts.AddOrUpdate("a", 1, (_, old) => old + 1);

Try it

C# Atomic updates in a ConcurrentDictionary

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# Queue, stack, bag and a blocking producer-consumer

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.

Choosing a collection

Need Use
Shared lookup table, many readers and writers ConcurrentDictionary<TKey, TValue>
FIFO work items ConcurrentQueue<T>
LIFO ConcurrentStack<T>
Unordered pool where each thread mostly takes its own items ConcurrentBag<T>
Bounded buffer with blocking producers and consumers BlockingCollection<T> or Channel<T>
Async producer/consumer Channel<T>
Read-mostly data that rarely changes an immutable or frozen collection swapped by reference

Usage notes

  • Compose with the atomic methods. TryAdd, TryRemove, TryUpdate, AddOrUpdate, GetOrAdd and TryDequeue do the check and the action in one step. if (!d.ContainsKey(k)) d[k] = v; does not.
  • Delegates in AddOrUpdate and GetOrAdd can run more than once and run outside the lock, so they must be free of side effects. Wrap expensive or one-time values in Lazy<T>, as in the first example.
  • Values are not protected. A ConcurrentDictionary<string, List<int>> makes the dictionary safe, not each List<int>. Use immutable values or lock around the mutation.
  • Count, ToArray and enumeration are moment-in-time snapshots; on a ConcurrentDictionary, Count takes all internal locks and is slow. Do not use Count == 0 to decide anything; use IsEmpty or just try the operation.
  • Enumeration never throws InvalidOperationException, but it may or may not include concurrent changes.
  • ConcurrentBag<T> is rarely the right choice. It is tuned for the case where the same thread adds and takes. For a queue use ConcurrentQueue<T>.
  • They do not replace a lock across several steps. When an invariant spans two collections or two keys, use a lock (or redesign).
  • Ordinary collections are not thread-safe. Concurrent writes to a List<T> or Dictionary<K,V> can corrupt them (infinite loops, lost items, exceptions), even when each thread uses different keys.