C# Reference ยท Collections
The ConcurrentDictionary<TKey,TValue> class
Reference for C# ConcurrentDictionary<TKey,TValue>: GetOrAdd, AddOrUpdate, TryAdd, TryUpdate, TryRemove, factory pitfalls and thread-safe counters.
ConcurrentDictionary<TKey,TValue> (namespace System.Collections.Concurrent) is a hash map that many threads can read and write at once. Reads take no lock, and writes lock only the part of the table (a "bucket group") they touch, so unrelated keys do not block each other.
Its API differs from Dictionary on purpose. A plain if (!d.ContainsKey(k)) d.Add(k, v) is a race: another thread can add the key between the two calls. Instead you use single atomic operations such as TryAdd, GetOrAdd and AddOrUpdate, which check and change in one step.
using System.Collections.Concurrent; var counts = new ConcurrentDictionary<string, int>(); counts.AddOrUpdate("apple", 1, (key, old) => old + 1);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class ConcurrentDictionary<TKey, TValue> where TKey : notnull { public ConcurrentDictionary(); public ConcurrentDictionary(IEqualityComparer<TKey>? comparer); public ConcurrentDictionary(int concurrencyLevel, int capacity); public bool TryAdd(TKey key, TValue value); public bool TryGetValue(TKey key, out TValue value); public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue); public bool TryRemove(TKey key, out TValue value); public bool TryRemove(KeyValuePair<TKey, TValue> item); public TValue GetOrAdd(TKey key, TValue value); public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory); public TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory); public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory); public TValue this[TKey key] { get; set; } public int Count { get; } public bool IsEmpty { get; } public ICollection<TKey> Keys { get; } public ICollection<TValue> Values { get; } }
| Name | Description |
|---|---|
key |
The key. Must not be null. |
value / addValue |
The value to store when the key is absent. |
valueFactory, addValueFactory |
Creates the value when needed. May run more than once. |
updateValueFactory |
Computes the new value from the key and the current one. May be retried. |
comparisonValue |
The value you expect to be stored now (compared with the default equality comparer). |
comparer |
Key equality, for example StringComparer.OrdinalIgnoreCase. |
Returns: TryAdd is false when the key exists. GetOrAdd and AddOrUpdate return the value that is stored afterwards (possibly one another thread added). TryUpdate is false when the key is missing or the current value is not comparisonValue.
Errors: ArgumentNullException for a null key, KeyNotFoundException from the indexer getter, OverflowException if the dictionary holds int.MaxValue items.
Usage notes
- Factories may run more than once, and their result may be discarded. If two threads call
GetOrAdd(k, factory)at the same moment, both factories can run and only one result is stored. Keep factories fast and side-effect free, or store aLazy<T>as shown above. - The factories are not called under a lock. That is intentional, to avoid deadlocks; it is also why compound logic belongs in the update function, not around the call.
Count,Keys,Valuesand enumeration are expensive or approximate.Countacquires all locks;KeysandValuesbuild a snapshot copy. PreferIsEmptyand enumerate the dictionary itself, which does not lock and never throws for concurrent changes (it may or may not show them).- Individual operations are atomic, groups are not. A read followed by a write is a race. Use
TryUpdatein a loop, orAddOrUpdate, for read-modify-write. - Not ordered. Do not rely on enumeration order.
- Cost: operations are O(1) on average, but slower per call than
Dictionarywhen there is only one thread. If a single thread owns the data, useDictionary. - Counters:
AddOrUpdate(k, 1, (_, v) => v + 1)works but allocates a closure per call if it captures; use astaticlambda. For hot counters considerConcurrentDictionary<K, StrongBox<int>>withInterlocked.