Today I am here to talk about Concurrent Collections in .NET. First we will discuss Concurrent Collections in general then go through ConcurrentDictionary in detail and cover what, when and how to use it.
To begin with, let’s put out some questions to understand the concept related to Concurrent Collections.
concept
What are the Concurrent collections and when to use them?
Concurrent collections (Namespace: System.Collections.Concurrent) are basically thread safe collections and are designed to be used in multithreading environment. They also provide type safety due to the generic implementation.
These collections should be used when they are getting changed or data is added/updated/deleted by multiple threads. If the requirement is only read in multithreaded environment then generic collections can be used.
If locking is needed at a few places, manual locking or synchronization techniques can also be used however if it is required at several places, using concurrent collection is a good choice.
Concurrent collections are designed to be used in cases when excessive thread safety is required, overly using manual locking can lead to deadlock and other issues.
Under the hood, concurrent collections use several algorithms to minimize the thread blocking.
What are the commonly used concurrent collections we have? Does concurrent collections addresses race conditions?
There are several types of concurrent collections but commonly used are as follows.
Out of the above list, ConcurrentDictionary can be used as a general purpose collection whereas others are mostly used in producer-consumer (i.e. dedicated threads for add-delete) scenarios.
Concurrent collections address the race condition and thread safety inside their implementation (e.g. inside AddOrUpdate method of ConcurrentDictionary) however it doesn’t guarantee the race conditions among threads between custom method calls.
Hope at this point, you understand what concurrent collections are and when to use them.
Now let’s see how to use them.
We will begin with concurrent dictionary as it’s the most commonly used.
dictionary
As mentioned earlier, Concurrent Dictionary is the general purpose collection and can be used in most of the cases. It has exposed several methods and properties and commonly used methods are as follows.
As you can see in the above output Key ‘Rewa’ is added with value 1 using GetOrAdd method as the key was not present in the collection.

Conclusion

In this article we have gone through what concurrent collections are and when to use them. We have discussed ConcurrentDictionary in detail including its common methods and illustrated the code and output. In the next part of the Concurrent Collection series, will talk about another collection and its uses.
You can also download the attached demo project (ConcurrentDictionaryDemo.zip) to go through the full source code used in the article.
Hope you have liked the article. Look forward to your comments/suggestions.