In the previous blog C# Dictionary with Examples, we have learned about C# Dictionary and how to use it for different purposes like Initialization, adding values, reading values, etc. In this article, we are going to learn about ConcurrentDictionary and how to use it for different purposes.
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads
The ConcurrentDictionary is a dictionary that allows you to add, fetch and remove items in a thread-safe way.
Before starting learning about ConcurrentDictionary, let us know why actually we need it and why we can not use C# Dictionary instead of C# ConcurrentDictionary. To make it clear please go through below code and try to write same in your VS and run it.
Just uncomment commented code – // dictionary.Add(i.ToString(), i.ToString()); and debug the code, There is error you’ll get stating “System.ArgumentException: ‘An item with the same key has already been added.'” which means in Dictionary once you allocate a key with the specific value you can never replace it. Fine! but what when you have to use Dictionary in the thread? In such a situation, you can use ConcurrentThread easily.
ConcurrentDictionary<TKey,TValue> provides some methods for performing different tasks like adding retrieving removing or updating key/value pairs in the dictionary
Add items in ConcurrentDictionary
TryAdd – We can use TryAdd method which basically attempts to add the specified key and value to the ConcurrentDictionary<TKey,TValue>
Updating Items in ConcurrentDictionary
TryUpdate – we can use TryUpdate method which basically checks whether the key has a specified value and if it does, updates the key with a new value. It is as same as CompareExchange method, except that we use it for dictionary elements.
Removing Item from ConcurrentDictionary
TryRemove – We can use TryRemove method which basically removes and return the value that has the specified key from them. It returns True if the object removed successfully and false if not.