C# ConcurrentDictionary with Examples

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.

ConcurrentDictionary

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

The ConcurrentDictionary is a dictionary that allows you to add, fetch and remove items in a thread-safe way.

Note:
1. The ConcurrentDictionary type resides in System.Collections.Concurrent. It was introduced in .NET 4.0.
2. It makes adding, removing and updating values in a lookup table on multiple threads easier.

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>

Note:
TryAdd methods returns true if key/value pair is added, and
returns false if the key already exists in the dictionary

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.

Note:
Compares two values for equality and, if they are equal, replaces the first value.

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.

Further Reading :
ConcurrentDictionary<TKey,TValue> Class

Leave a Reply