⚙️ C# / .NET Intermediate

What is a ConcurrentDictionary and when should you use it?

Answer

ConcurrentDictionary<TKey, TValue> is a thread-safe dictionary in System.Collections.Concurrent that allows multiple threads to read and write simultaneously without external locking. Uses fine-grained locking (striped locks) for better throughput than a single lock on a regular dictionary. Key methods: GetOrAdd(key, valueFactory) — atomically add if missing. AddOrUpdate(key, addValue, updateFactory) — atomically add or update. TryGetValue(key, out value), TryRemove(key, out value). Use when: multiple threads need to read/write shared state concurrently (cache, counters, request tracking). Caution: GetOrAdd with a factory is not atomically guaranteed — the factory might be called multiple times (only one value is stored, but the factory runs on multiple threads). For true atomic create-once semantics, use Lazy<T>. For simple counters, prefer Interlocked.Increment. Do not use regular Dictionary in multi-threaded contexts — it will corrupt internal state.