Introduction
Dear reader, as we all know, data concurrency (fetching data from the database and inserting data into the database) without any duplication is one of the most important parts of software development. If we are not able to solve this problem, then your software is not able to move into the production environment.
So I thought I should write an article to give my readers a better idea on how to solve these kind of problems.
In this article, we will try to learn when we work on a multi-threaded application, how we can apply the best generic collection which is called ConcurrentDictionary in C#
So on the basis of that, I am trying to explain in the following section:
- Definition
- Useful Methods
- TryAdd(TKey, TValue)
- TryGetValue(TKey, TValue)
- TryRemove(TKey, TValue)
- TryUpdate(TKey, TValue, TValue)
- Clear()
- ContainsKey(TKey)
- ToArray
- ToDictionary
- ToList
- Useful Properties
Definition
ConcurrentDictionary is a generic collection, ConcurrentDictionary was introduced in .NET framework 4.0 as it is available in System.Collections.Concurrent namespace, this generic collection is used in the case of a multi-threaded application.
So in this case, we do not need to use the lock keyword to lock the function.
As you know, Microsoft in C# already provided a generic collection that is called Dictionary.
So why do we need ConcurrentDictionary in C#?
The answer is that ConcurrentDictionary provides a thread-safe functionality.
So the question is, what is the actual meaning of thread-safe in C#? As you know, when we are working on real-time projects, then it is possibile to work on a multi-threaded application to add and get items from the dictionary. the result may be wrong because the Dictionary is not thread-safe.
ConcurrentDictionary is, by default, thread-safe, which provides the correct result.
Let's see it with a simple example:
- public class Program {
- static Dictionary < string, int > _mydic = new Dictionary < string, int > ();
- static ConcurrentDictionary < string, int > _mydictConcu = new ConcurrentDictionary < string, int > ();
- static void Main() {
- Thread mythread1 = new Thread(new ThreadStart(InsertData));
- Thread mythread2 = new Thread(new ThreadStart(InsertData));
- mythread1.Start();
- mythread2.Start();
- mythread1.Join();
- mythread2.Join();
- Thread mythread11 = new Thread(new ThreadStart(InsertDataConcu));
- Thread mythread21 = new Thread(new ThreadStart(InsertDataConcu));
- mythread11.Start();
- mythread21.Start();
- mythread11.Join();
- mythread21.Join();
- Console.WriteLine($ "Result in Dictionary : {_mydic.Values.Count}");
- Console.WriteLine("********************************************");
- Console.WriteLine($ "Result in Concurrent Dictionary : {_mydictConcu.Values.Count}");
- Console.ReadKey();
- }
- static void InsertData() {
- for (int i = 0; i < 100; i++) {
- _mydic.Add(Guid.NewGuid().ToString(), i);
- }
- }
- static void InsertDataConcu() {
- for (int i = 0; i < 100; i++) {
- _mydictConcu.TryAdd(Guid.NewGuid().ToString(), i);
- }
- }
- }
- // Output
- Result in Dictionary: 189 ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** Result in Concurrent Dictionary: 200

As you see in the output, in the case dictionary we are only getting 189, while in ConcurrentDictionary, we are getting 200 as the expected result.
So we may or may not get the expected result in the dictionary.
I hope the basic understanding is clear now.
Let's learn its useful methods:
TryAdd(TKey, TValue)
This method is used to add the item in ConcurrentDictionary:
- static void Main(string[] args) {
- ConcurrentDictionary < string, string > _myConcuDict = new ConcurrentDictionary < string, string > ();
- _myConcuDict.TryAdd("1", "A");
- _myConcuDict.TryAdd("2", "B");
- _myConcuDict.TryAdd("3", "C");
- }
This TryAdd method return bool value like this: public bool TryAdd(TKey key, TValue value);
So if we add any value and it is added successfully, then it will return true, otherwise, it will return false.
- static void Main(string[] args) {
- ConcurrentDictionary < string, string > _myConcuDict = new ConcurrentDictionary < string, string > ();
- //returns true
- bool r1 = _myConcuDict.TryAdd("1", "A");
- //returns true
- bool r2 = _myConcuDict.TryAdd("2", "B");
- //returns false;
- bool r3 = _myConcuDict.TryAdd("1", "C");
- }

Mahadevan AnnamalaiPosted Jan 22, 2025, 11:54 AM
Thanks well explained.
Varun SetiaPosted Oct 23, 2020, 3:26 AM
Very nicely explained. Thanks for sharing.
Guest UserPosted Oct 21, 2020, 1:25 PM
Very informative article