There are two ways I've assigned values to a existing key in a concurrent dictionary in my current project.
A. concurrentDictionary1[key] = value
;
and
B. concurrentDictionary2.AddOrUpdate(key, value, (k, v) => value);
If I know that the 'key' exists, are these functionally equivalent?
Is protection offered by the concurrency of the Concurrent Dictionary bypassed with method 'A'?
What is the difference here? What are the reasons for choosing one over the other?
I looked through the documentation at msdn, and it seems they only initialize a concurrent dictionary with method 'A', not update it.
It is thread-safe in the sense that the internal state of the ConcurrentDictionary will not be corrupted. This is the main guarantee offered by this class.
It is thread safe in your usage. It becomes not thread safe when the delegate passed to AddOrUpdate has side effects, because those side effects may be executed twice for the same key and existing value.
ConcurrentDictionary<TKey, TValue> Class Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
This is an old question, but no one answered why you would use one over the other.
Choose A (the indexer) if you want to add or update and the update is not dependent on the existing value.
Choose B (AddOrUpdate) if you want to add or update and the update depends on an existing value. AddOrUpdate will do the update atomically.
So in the case in the question, you want to use the indexer. It's simpler, easier to read, and probably faster since you aren't creating an anonymous function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With