
Why ConcurrentDictionary Alone Won't Make Your Code Thread-Safe
- كاتب موثّق
- .NET 10
محتويات المقال
ConcurrentDictionary<string, decimal>, filled with GetOrAdd(currency, LoadRate). The team chose it "so the cache is thread-safe." Yet after every deploy, the rate provider reports a burst of duplicate requests for the same currency, sometimes enough to hit its rate limit. And the request counter on the admin page, kept in another ConcurrentDictionary, ends each day lower than the access log says. No exception, no corrupted dictionary, just wrong numbers.
The common misconception
ConcurrentDictionary, the code around it is thread-safe. Its methods handle the locking, so a check followed by an update, or a GetOrAdd with a factory, can't race.
Dictionary, which needs your own synchronization for concurrent writes, it keeps its internal state consistent however many threads write at once. And most of the time, the code built on top of it looks correct in tests, where calls rarely overlap.
What actually happens
Each call is atomic; your sequence isn't
TryAdd, TryGetValue, TryRemove and the indexer are each : other threads see them happen entirely or not at all. But "read the count, add one, write it back" is two calls, and the docs point out that one thread can read a value while another immediately replaces it. Two threads can read 41, both write 42, and one increment is gone. The same hides in ContainsKey followed by an add, or a TryGetValue followed by a decision based on what it found: by the time you act, the answer may be stale.
GetOrAdd runs your factory outside the lock
valueFactory you pass to GetOrAdd outside that lock. The docs spell out the consequence: when several threads call GetOrAdd for a missing key at the same time, the factory may run on each of them, though only one value is stored and every caller gets that stored value back. If the factory is pure, that's only wasted work. If it calls an API, opens a connection or writes a log line, those side effects happen once per racing thread. That's the deploy-time burst: a cold cache, many requests for "EUR" at once, and each one ran LoadRate. AddOrUpdate works the same way for both of its delegates.
The value itself isn't protected
List<T> or any mutable object, two threads calling dict[key].Add(item) modify the same list at once, and List<T> has no thread safety of its own. Prefer immutable values that you replace as a whole, or protect the object separately.
The lost increments, fixed
using System.Collections.Concurrent;var hits = new ConcurrentDictionary<string, int>();Parallel.For(0, 10_000, _ =>{ hits.TryGetValue("home", out int count); // step 1: read hits["home"] = count + 1; // step 2: write, maybe stale});Console.WriteLine(hits["home"]); // often far below 10000, varies per runusing System.Collections.Concurrent;var hits = new ConcurrentDictionary<string, int>();Parallel.For(0, 10_000, _ =>{ // one call: the update is applied to the latest value, retried if needed hits.AddOrUpdate("home", 1, (_, count) => count + 1);});Console.WriteLine(hits["home"]); // 10000AddOrUpdate computes the new value from the current one and stores it only if nobody changed the value in the meantime; otherwise it calls your delegate again. That's why Microsoft's own example, 10,000 concurrent AddOrUpdate calls on one key, ends at exactly 10,000, and also why the delegate must not have side effects.
One factory call per key
Lazy<T> instead of the value. Racing threads may each create a cheap Lazy object, but only the one that ends up in the dictionary is ever asked for its Value, and by default a Lazy<T> lets only one thread run its factory:
using System.Collections.Concurrent;public sealed class RateCache(IRateApi api){ private readonly ConcurrentDictionary<string, Lazy<Task<decimal>>> _rates = new(); public Task<decimal> GetAsync(string currency) => _rates.GetOrAdd(currency, c => new(() => api.GetRateAsync(c))).Value;}GetOrAdd version ran the factory many times; this version called the API once. Storing the Task also lets every caller await the same in-flight request.
Which calls are safe on their own
TryAdd, TryRemove, indexer get or set | ||
TryGetValue, then set the indexer | ||
ContainsKey, then add | ||
GetOrAdd with a factory | ||
AddOrUpdate | ||
How to apply it in your project
Search for two-step access Look for ContainsKey,TryGetValueor an indexer read followed by a write to the same dictionary. Replace each pair withAddOrUpdate,GetOrAdd,TryAddorTryUpdate, which compares the current value before replacing it.Make factories pure or lazy Keep GetOrAddandAddOrUpdatedelegates free of I/O, logging and counters. When creating the value is expensive or has side effects, storeLazy<T>.Make values immutable Store records or immutable collections and replace them as a whole, instead of mutating a shared list or object in place. Lock multi-step logic When an operation spans several keys or steps, use a Dictionarywith alockaround the whole operation, and keep the locked section short.
Key takeaways
ConcurrentDictionarymakes each call atomic, not the sequence of calls in your code.Read-then-write and check-then-act patterns still race; use AddOrUpdate,GetOrAdd,TryAddorTryUpdateinstead.Factories passed to GetOrAddandAddOrUpdaterun outside the lock and may run several times; wrap expensive ones inLazy<T>.The dictionary doesn't protect mutable values or multi-key logic; use immutable values and a lockwhere steps belong together.
التعليقات (0)