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.
var counts = new ConcurrentDictionary<string, int>(); counts.AddOrUpdate("a", 1, (_, old) => old + 1);
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.
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,GetOrAddandTryDequeuedo the check and the action in one step.if (!d.ContainsKey(k)) d[k] = v;does not. - Delegates in
AddOrUpdateandGetOrAddcan run more than once and run outside the lock, so they must be free of side effects. Wrap expensive or one-time values inLazy<T>, as in the first example. - Values are not protected. A
ConcurrentDictionary<string, List<int>>makes the dictionary safe, not eachList<int>. Use immutable values or lock around the mutation. Count,ToArrayand enumeration are moment-in-time snapshots; on aConcurrentDictionary,Counttakes all internal locks and is slow. Do not useCount == 0to decide anything; useIsEmptyor 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 useConcurrentQueue<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>orDictionary<K,V>can corrupt them (infinite loops, lost items, exceptions), even when each thread uses different keys.