The MSDN documentation of System.Collections.Concurrent.ConcurrentDictionary says:
Thread Safety
All public and protected members of
ConcurrentDictionary<TKey, TValue>
are thread-safe and may be used concurrently from multiple threads. However, members accessed through one of the interfaces theConcurrentDictionary<TKey, TValue>
implements, including extension methods, are not guaranteed to be thread safe and may need to be synchronized by the caller.
(emphasis mine)
This seems self-contradictory. "All members are thread-safe. But members [sometimes] are not thread-safe."
I do understand that extension methods are of course not guaranteed to be thread safe.
But what do they mean by "accessed through one of the interfaces"? Is TryGetValue
(a member of the IDictionary<TKey, TValue>
interface) thread-safe?
Notice the section of the documentation that covers explicit interface implementations. E.g. the class implements IDictionary.Add
. This method is not a public or protected member of the class, but may be accessed via the IDictionary
interface. It is these such members that are not being guaranteed to be thread safe.
Due to Explicit vs Implicit interface implementation.
If you take a look at the source code for ConcurrentDictionary<TKey, TValue>
you may see that there are some methods that explicitly implement an interface (like object IDictionary.this[object key]
) which although internally call the thread-safe version of the same operation this behavior may change in the future.
Think of it as division of responsibility:
If I (as a class) receive an instance of ConcurrentDictionary<TKey, TValue>
I know that it's that instance's responsibility to perform operations in a thread-safe manner.
However, if I (again as a class) receive an instance of IDictionary<TKey, TValue>
then I should be aware if there should or shouldn't be a thread-safety concern. If there is no such concern I just use the dictionary as it is but if thread-safety is required it's my responsibility to perform all operations in a thread-safe manner.
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