If you want to update a key of a ConcurrentDictionary
regardless of its current value, you can just use the set accessor of the indexer:
var dictionary = new ConcurrentDictionary<int, string>();
dictionary[1] = "Hello";
dictionary[2] = "World";
dictionary[1] = "Goodbye";
Console.WriteLine(String.Join(", ", dictionary));
Output:
[1, Goodbye], [2, World]
If each thread is working with an isolated set of keys, updating a ConcurrentDictionary
like this might be sufficient. But if multiple threads are competing for updating the same keys, chaos might ensue. In those cases it might be desirable to use the TryUpdate
method, or more frequently the AddOrUpdate
method. These methods allow to update conditionally the dictionary, with the checking and updating being an atomic operation.
The following question might offer some insights about how this API can be used in practice:
Is there a way to use ConcurrentDictionary.TryUpdate
with a lambda expression?