Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Concurrent Dictionary not have a visible Add() Method?

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

like image 421
Lenny D Avatar asked Apr 05 '13 08:04

Lenny D


People also ask

What is the difference between Dictionary and concurrent Dictionary?

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".

What is the purpose of concurrent Dictionary TKey TValue class?

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

How does concurrent Dictionary work?

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.

Do you need to lock concurrent Dictionary?

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.


1 Answers

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.

like image 158
Sam Harwell Avatar answered Oct 04 '22 13:10

Sam Harwell