Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which members of .NET's ConcurrentDictionary are thread-safe?

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 the ConcurrentDictionary<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?

like image 479
Peter Avatar asked Jul 12 '16 07:07

Peter


2 Answers

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.

like image 164
Damien_The_Unbeliever Avatar answered Nov 15 '22 20:11

Damien_The_Unbeliever


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.

like image 33
RePierre Avatar answered Nov 15 '22 20:11

RePierre