2.3 — Concurrent Collections¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.2 Collections and Big-O · Next: 2.4 yield and iterators
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- The normal collections (
List,Dictionary) are not safe when several threads write to them at once. They can corrupt themselves or hang forever. ConcurrentDictionary<K,V>is the one you will actually use. In ASP.NET Core, every request runs on its own thread, so any shared collection needs this.- Thread-safe on each operation is not the same as thread-safe overall. Two safe calls in a row can still race.
The concept¶
In a web application, many requests are handled at the same time, on different threads.
If they all touch the same Dictionary, they are all reaching into the same object at once.
Why is that dangerous? Because operations that look like one step are really several. Adding
to a Dictionary might mean: work out the slot, check if it is full, resize the internal
array, copy everything across, write the value. If a second thread interrupts halfway
through, it sees a half-rebuilt structure.
A picture: two people editing the same paper address book at the same time. One is midway through copying every entry onto a bigger sheet because the old one filled up. The other writes a new entry onto the old sheet. That entry vanishes. Or worse, the book ends up with a page pointing at itself and anyone reading it walks in circles forever.
That last one is real. A corrupted Dictionary in .NET Framework could put a thread into an
infinite loop, pinning a CPU core at 100% until the process was restarted.
The System.Collections.Concurrent namespace has replacements that handle this properly.
How it works¶
The types¶
| Concurrent type | Replaces | Use it for |
|---|---|---|
ConcurrentDictionary<K,V> |
Dictionary<K,V> |
Shared lookups. By far the most used. |
ConcurrentQueue<T> |
Queue<T> |
Work items processed oldest-first |
ConcurrentStack<T> |
Stack<T> |
Work items processed newest-first |
ConcurrentBag<T> |
List<T> (unordered) |
Many threads adding, order irrelevant |
BlockingCollection<T> |
— | Producer/consumer with a size limit |
There is deliberately no ConcurrentList<T>. A list is about position, and positions
stop being meaningful when other threads are inserting and removing underneath you. If you
need a shared ordered list, either lock around it or use ImmutableList<T>.
ConcurrentDictionary — the important one¶
private readonly ConcurrentDictionary<string, User> _cache = new();
_cache["key"] = user; // safe
_cache.TryGetValue("key", out var found); // safe
_cache.TryRemove("key", out var removed); // safe
The methods that make it genuinely useful are the combined ones:
// GetOrAdd — if the key exists return it, otherwise create, store and return it.
// The whole check-and-add is ONE atomic operation.
var user = _cache.GetOrAdd(userId, id => LoadUserFromDatabase(id));
// AddOrUpdate — insert if new, otherwise compute a new value from the old one
_cache.AddOrUpdate(
key: userId,
addValue: 1, // if not present, store 1
updateValueFactory: (k, old) => old + 1); // if present, add 1 to it
Without GetOrAdd, you would write this — and it is broken:
// BROKEN even with a ConcurrentDictionary
if (!_cache.ContainsKey(id)) // thread A: not there
{ // thread B: also not there
_cache[id] = Load(id); // BOTH load. Both write. Wasted work,
} // and possibly two different objects.
Each individual call is thread-safe. The sequence is not. This is the single most important idea in this note.
⚠️ The factory can run more than once¶
GetOrAdd is atomic in what it stores — only one value ever wins. But the factory
function you pass in is not locked, and can be executed by several threads at the same
time:
var user = _cache.GetOrAdd(id, key =>
{
Console.WriteLine("Loading..."); // this CAN print twice for the same key
return LoadFromDatabase(key); // only one result is kept
});
That is a deliberate design choice — holding a lock while running arbitrary user code is how you get deadlocks. But it means:
- If the factory is expensive, you may pay for it several times.
- If the factory has side effects (writes a file, sends an email), those happen more than once.
The fix when it matters is to store a Lazy<T>, because Lazy guarantees its factory runs
only once:
private readonly ConcurrentDictionary<string, Lazy<User>> _cache = new();
var user = _cache
.GetOrAdd(id, key => new Lazy<User>(() => LoadFromDatabase(key)))
.Value; // only the winning Lazy is ever evaluated
BlockingCollection<T> — producer and consumer¶
Useful when one part of your code produces work and another consumes it, and you want the producer to slow down if the consumer falls behind:
var queue = new BlockingCollection<Job>(boundedCapacity: 100);
// Producer — blocks if there are already 100 waiting
Task.Run(() =>
{
foreach (var job in GetJobs())
queue.Add(job);
queue.CompleteAdding(); // signals "no more coming"
});
// Consumer — blocks until an item arrives, exits when adding is complete
Task.Run(() =>
{
foreach (var job in queue.GetConsumingEnumerable())
Process(job);
});
The capacity limit is the point. Without it, a fast producer builds an unbounded queue in memory until the process runs out.
In modern ASP.NET Core, prefer System.Threading.Channels for this. It does the same
job with proper async support, so consumers await instead of blocking a thread. See
21.1.
Code¶
The realistic ASP.NET Core case — a shared in-memory cache in a singleton service:
public class ExchangeRateService(IHttpClientFactory factory)
{
// Singleton service, so this dictionary is shared by EVERY request
// happening at the same time. It MUST be concurrent.
private readonly ConcurrentDictionary<string, Lazy<Task<decimal>>> _rates = new();
public Task<decimal> GetRateAsync(string currency)
{
return _rates.GetOrAdd(
currency,
key => new Lazy<Task<decimal>>(() => FetchRateAsync(key))
).Value;
}
private async Task<decimal> FetchRateAsync(string currency)
{
var client = factory.CreateClient("rates");
return await client.GetFromJsonAsync<decimal>($"/rate/{currency}");
}
}
Why Lazy<Task<decimal>> and not just Task<decimal>? Because without Lazy, fifty
simultaneous requests for the same currency could each start their own HTTP call before any
of them finished. With Lazy, only one call is ever made and the other forty-nine await
the same task. That pattern is called stampede protection —
19.4 covers it properly.
But in a real ASP.NET Core app, reach for IMemoryCache first. It gives you expiry,
size limits and eviction, which a raw ConcurrentDictionary does not — a dictionary that
only ever grows is a memory leak. See 19.2.
Interview questions¶
Q: Why can't you just use a Dictionary in a multi-threaded application?
Because its operations are not atomic. Adding an item can involve resizing the internal array and copying everything into it, and if another thread reads or writes partway through that, it sees an inconsistent structure. In the worst case the internal links become circular and a reading thread spins forever at 100% CPU. In ASP.NET Core this matters constantly, because requests are handled concurrently on different threads, so anything stored in a singleton is shared across all of them.
Q: What does GetOrAdd do, and what is the catch?
It returns the existing value for a key, or creates one with the factory you supply, stores
it and returns that — as a single atomic operation, so you avoid the classic check-then-add
race. The catch is that only the storing is atomic. The factory itself is not locked, so
several threads can run it simultaneously for the same key even though only one result is
kept. If the factory is expensive or has side effects, you wrap the value in a Lazy<T>,
because Lazy does guarantee its factory runs once.
Q: Is a ConcurrentDictionary enough to make my code thread-safe?
No, and this is the important distinction. Each individual method on it is thread-safe, but
a sequence of calls is not. Writing if (!dict.ContainsKey(k)) dict[k] = value is still
racy, because another thread can insert between the check and the write. That is exactly why
the combined methods like GetOrAdd and AddOrUpdate exist — they collapse the sequence
into one atomic step.
Q: Why is there no ConcurrentList<T>?
Because a list is defined by position, and position is meaningless once other threads can insert and remove concurrently — index 5 could refer to a different item by the time you use it, and an index that was valid when you checked could be out of range a moment later. There is no sensible way to make that safe. If you need shared ordered data, you either lock around a normal list or use an immutable collection where every change produces a new version.
Traps ⚠️¶
- Thread-safe operations do not make thread-safe logic. Check-then-act across two calls is still a race, even on a concurrent collection.
- The
GetOrAddfactory can run several times. Only one result is stored, but the work may be done more than once. Wrap inLazy<T>if that matters. - Concurrent collections are slower for single-threaded use. They pay for synchronisation you are not using. Do not use them "just in case".
Counton a concurrent collection is a snapshot and may be stale the instant you read it. Never use it for a decision that must be exact.- Enumerating a concurrent collection gives you a moment-in-time view. Items may be added or removed while you loop; you will not see a consistent snapshot.
- A
ConcurrentDictionarythat only grows is a memory leak. It has no eviction. UseIMemoryCachefor anything cache-shaped. ConcurrentBagis optimised for the same thread adding and removing. If one thread produces and another consumes,ConcurrentQueueis usually faster.
Related¶
- 2.2 Collections and Big-O — the non-thread-safe originals
- 2.18 Thread safety —
lock,Interlockedand the alternatives - 1.5 static — why static mutable state needs this
- 6.3 Service lifetimes — singletons are shared across requests
- 19.2 IMemoryCache — the right tool for caching
- 21.1 Background services — Channels instead of
BlockingCollection