'What's the reason for the comparisonValue argument in the ConcurrentDictionary.TryUpdate method?
Why do we need third argument comparisonValue in ConcurrentDictionary.TryUpdate method?
And why will updating not succeed if already existed value is not equal to comparisonValue? Can't we just replace existed value with the new one just like in normal Dictionary<,>?
This is the signature:
public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)
Solution 1:[1]
The point is that you're using concurrent dictionary for scenarios with concurrent access to the dictionary. You don't know who (and how) changed the dictionary in the meantime. Passing a comparison value is a very simple and effective way of only doing the change if the state of the dictionary is the same one you expect.
If you expect collisions to be relatively rare, this is a very efficient and performant way of handling shared state (no need for locking, and thus stopping all access). This pattern is the basis of lock-free code; you see it even on the hardware level. You can look up Compare and Exchange (or Compare and Swap) for more information.
Solution 2:[2]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Theodor Zoulias |
