Usage Concurrent Dictionary in .NET

Dheeraj Kumar Gunti

Reading Time : ( words)

Hi All,

Welcome back to Knowledge Base.

When we are working with Dictionary Object we need to take care that it should be thread-safe. In earlier versions of .NET Framework (Before 4.0) we need to go with locking mechanism for handling object when we are dealing with multiple threads.

In .NET Framework 4.5 onwards, we got one more kind of Dictionary which is ConcurrentDictionary (MSDN). Name itself indicates Concurrency (In simple terms can be handled in multiple requests).

ConcurrentDictionary can be found at System.Collections.Concurrent namespace.

ConcurrentDictionary can be easily used for all the CRUD operations on multiple threads.

We have couple of methods which we can use in performing operations.

  • TryAdd - Attempts to add the specified key and value to the ConcurrentDictionary. Return true if the key/value pair was added to the ConcurrentDictionary successfully. If the key already exists, this method returns false.
  • TryGetValue - Attempts to get the value associated with the specified key from the ConcurrentDictionary. Returns true if the key was found in the ConcurrentDictionary otherwise, false.
  • TryRemove - Attempts to remove and return the value with the specified key from the ConcurrentDictionary. Returns true if an object was removed successfully. otherwise, false.
  • TryUpdate - Compares the existing value for the specified key with a specified value, and if they are equal, updates the key with a third value. Returns true if the value with key was equal to comparisonValue and replaced with newValue. otherwise, false.

IsEmpty - It is similar to Object.Count = 0 and it won't return negative numbers. It return empty when there are no elements in the dictionary.

Working on specific process like this is it make the system work in multi threaded environments and need to have collection available at any point of time with out it being corrupted. We call them has fail-safe methods.

Simple Example: