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);
- }
- }
- }
-
- 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 > ();
-
- bool r1 = _myConcuDict.TryAdd("1", "A");
-
- bool r2 = _myConcuDict.TryAdd("2", "B");
-
- bool r3 = _myConcuDict.TryAdd("1", "C");
- }
Here, in this example, r3 is returned as false because the item key already exists in ConcurrentDictionary.
TryGetValue(TKey, TValue)
In this method, we will get an item by the given key:
- static void Main(string[] args) {
- ConcurrentDictionary < string, string > _myConcuDict = new ConcurrentDictionary < string, string > ();
- bool firstItem = _myConcuDict.TryAdd("1", "A");
- bool secondItem = _myConcuDict.TryAdd("2", "B");
- string item1;
- string item2;
-
- bool isItemExists1 = _myConcuDict.TryGetValue("1", out item1);
- Console.WriteLine(item1);
-
- bool isItemExists2 = _myConcuDict.TryGetValue("3", out item2);
- Console.WriteLine(item2);
- }
Here, in TryGetValue, 3 does not exist in ConcurrentDictionary, so it will print blank.
Here, we could also use an iteration to get all the items:
- foreach(var item in _myConcuDict) {
- Console.WriteLine(item.Key + "-" + item.Value);
- }
TryRemove(TKey, TValue)
ConcurrentDictionary also provides the ability to remove a specific item by a given key.
- 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");
- _myConcuDict.TryAdd("4", "D");
- string itmRemove;
- bool r1 = dictionary.TryRemove("2", out itmRemove);
- Console.WriteLine(removedItem);
- }
In this example, it will remove item 2 given the key.
TryUpdate(TKey, TValue, TValue)
This method is used to update the item if given a key whose value matches the condition.
- 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");
- _myConcuDict.TryAdd("4", "D");
- string newItem;
- bool returnTrue = dictionary.TryUpdate("1", "P", "A");
- dictionary.TryGetValue("1", out newItem);
- Console.WriteLine(newValue);
- bool returnsFalse = dictionary.TryUpdate("2", "Q", "CDD");
- dictionary.TryGetValue("2", out newItem);
-
- Console.WriteLine(newValue);
- }
Clear()
This method is used to remove all items from ConcurrentDictionary.
ContainsKey(TKey)
Sometimes, we are required to check if a particular key item exists or not in a given collection.
So here, ConcurrentDictionary also provides a method to check it.
-
- bool r1 = dictionary.ContainsKey("1");
-
- bool r2 = dictionary.ContainsKey("5");
Note
Sometimes we are required to copy only a collection to another collection.
For that, ConcurrentDictionary provides various casting methods to do this.
- ToArray
- ToDictionary
- ToList
- 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");
- _myConcuDict.TryAdd("4", "D");
-
- KeyValuePair < string, string > [] keyValues = _myConcuDict.ToArray();
-
- Dictionary < string, string > myDict = _myConcuDict.ToDictionary(w => w.Key, m => m.Value);
-
- List < KeyValuePair < string, string >> lst = _myConcuDict.ToList();
- }
Properties
The following properties can be used based on our requirements:
- Count : This property is use to count the record
- IsEmpty : This property is use to check ConcurrentDictionary is empty or not
- var isEmplty = _mydictConcu.IsEmpty
- Item[TKey]: This property is used to get or set for particular item
- Keys : This projects is used to get list of items keys in given ConcurrentDictionary
- Values : This property is used to get the value of given ConcurrentDictionary.
Summary
ConcurrentDictionary was introduced in .NET 4.0 and is available in the System.Collections.Concurrent namespace. It is thread-safe and internally uses locking. It is useful in the case of a multi-threaded application. However, ConcurrentDictionary is slower than Dictionary.
Thank you for taking your valuable time to read the full article.