I was just wondering how it was possible that ConcurrentDictionary does not have an Add method which is visible in the Visual Studio IDE. I only seem to get the TryX Methods e.g TryAdd, TryUpdate etc.
I can see that the ConcurrentDictionary
implements IDictionary
and if I cast it to IDictionary
I get the Add Method back.
I have looked at the class through iLSpy and I can see the Add Method is fully implemented and does actually call the Concurrent TryAdd
Method under the hood.
I was expecting to see some sort of Attribute on the Add method to surpress it but I am not seeing anything.
Has this been baked into the IDE by Microsoft to hide the Add method by default ??
If someone could shed some light on this it would be appreciated
The name kind of explains it self. You use a ConcurrentDictionary when you need Concurrent access to a Dictionary. The thing to search for is "thread safety".
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.
ConcurrentDictionary<TKey,TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.
They are discouraging the use of the Add
method because the method throws an exception if the key is already present in the dictionary. For most dictionaries, the developer can write code in a way to guarantee that the exception will not be thrown under any normal scenario. However, to perform this operation (Contains
followed by Add
) with a concurrent dictionary, you would need to use exclusive locks in methods accessing the dictionary, which defeats the entire purpose of a concurrent dictionary.
TryAdd
combines the Contains
and Add
checks without requiring you to lock the dictionary, and allows you to once again write code that won't throw an exception in normal scenarios.
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