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.
Previous
What is the difference between IQueryable and IEnumerable in LINQ?
Next
What is the Observer pattern and how is it implemented in C#?
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?