Back to results for “Collections”
C# › Collections

What is the performance and thread-safety difference between ConcurrentDictionary<TKey,TValue> and a regular Dictionary<TKey,TValue> guarded by a manual lock?

Advanced

Answer

ConcurrentDictionary uses fine-grained internal locking (per-bucket/segment) allowing MULTIPLE threads to read/write DIFFERENT parts of the dictionary concurrently with less contention, whereas wrapping a plain Dictionary in a single 'lock' serializes ALL access — one thread at a time, even for operations on completely unrelated keys — making ConcurrentDictionary generally faster under real concurrent load, though single-threaded access to a plain Dictionary is still slightly faster due to lower overhead.
var concurrentCache = new ConcurrentDictionary<string, int>();
concurrentCache.AddOrUpdate("visits", 1, (key, oldValue) => oldValue + 1); // thread-safe atomic update

// vs. manual locking around a plain Dictionary:
lock (lockObject) { dictionary["visits"] = dictionary.GetValueOrDefault("visits") + 1; }
Real-world example Building a thread-safe, high-throughput in-memory cache accessed concurrently by many request-handling threads in a web server.

Common follow-ups: Why might a single 'lock' around a plain Dictionary actually outperform ConcurrentDictionary under LOW contention (few concurrent threads)?