الانتقال إلى المحتوى
.NETC#· 6 دقائق للقراءة

Why ConcurrentDictionary Alone Won't Make Your Code Thread-Safe

Every call is safe, but your sequence of calls isn't, and GetOrAdd may run its factory more than once. Where the races hide and how to close them.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A pricing service caches exchange rates in a 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

The belief: once shared data lives in a 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.

It's half true, and the true half is strong. Microsoft's docs call it a thread-safe dictionary and say you don't need locks of your own to add or remove items. Unlike a plain 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 the dictionary protects is its own state during each call. Your logic lives between the calls, and nothing protects that.

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

To avoid running unknown code while holding its internal lock, the dictionary calls the 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

The dictionary guards the slot that holds each value, not the object in it. If the value is a 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

Here is the counter before and after, compressed into a single parallel loop:

C# Program.cs
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 run

On a multi-core machine, the first version prints a different number on almost every run, often a fraction of 10,000. The second always prints 10,000. AddOrUpdate 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

To make the expensive work run once, store a 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:

C# RateCache.cs
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;}

With 64 concurrent requests for a missing currency, a test of the plain 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

PatternAtomic?What can go wrong
TryAdd, TryRemove, indexer get or setYes, each callNothing inside the call
TryGetValue, then set the indexerNo, two callsLost updates
ContainsKey, then addNo, two callsAnother thread adds first
GetOrAdd with a factoryThe store is; the factory isn'tFactory runs several times
AddOrUpdateThe store is; the delegates aren'tDelegates run several times
Changing a mutable valueNot coveredRaces inside the value

How to apply it in your project

  1. Search for two-step accessLook for ContainsKey, TryGetValue or an indexer read followed by a write to the same dictionary. Replace each pair with AddOrUpdate, GetOrAdd, TryAdd or TryUpdate, which compares the current value before replacing it.
  2. Make factories pure or lazyKeep GetOrAdd and AddOrUpdate delegates free of I/O, logging and counters. When creating the value is expensive or has side effects, store Lazy<T>.
  3. Make values immutableStore records or immutable collections and replace them as a whole, instead of mutating a shared list or object in place.
  4. Lock multi-step logicWhen an operation spans several keys or steps, use a Dictionary with a lock around the whole operation, and keep the locked section short.

Key takeaways

  • ConcurrentDictionary makes each call atomic, not the sequence of calls in your code.
  • Read-then-write and check-then-act patterns still race; use AddOrUpdate, GetOrAdd, TryAdd or TryUpdate instead.
  • Factories passed to GetOrAdd and AddOrUpdate run outside the lock and may run several times; wrap expensive ones in Lazy<T>.
  • The dictionary doesn't protect mutable values or multi-key logic; use immutable values and a lock where steps belong together.

📚 المصادر

  1. Thread-safe collections — Microsoft Learn
  2. Add and remove items from a ConcurrentDictionary — Microsoft Learn
  3. ConcurrentDictionary<TKey,TValue>.GetOrAdd: Remarks — Microsoft Learn
  4. LazyThreadSafetyMode Enum — Microsoft Learn
  5. The lock statement (C# reference) — Microsoft Learn

التعليقات (0)