1024programmer Asp.Net Basic use of c# Dictionary dictionary and thread-safe dictionary

Basic use of c# Dictionary dictionary and thread-safe dictionary

Basic use of c# Dictionary dictionary and thread-safe dictionary

In C#, a dictionary is a special collection used to store key/value pairs. This is an associative array in which each element contains a key and a value.

The following is an example of a simple C# dictionary:

//Dictionary: generic; key - value, addition, deletion, checking and modification are all very fast;
                 // If the amount of data in the dictionary is too large, it will also affect efficiency.
                 // Dictionary is not thread-safe ConcurrentDictionary
                 Console.WriteLine("******************Dictionary******************");
                 Dictionary dic = new Dictionary();
                 dic.Add(1, "HaHa");
                 dic.Add(5, "HoHo");
                 dic.Add(3, "HeHe");
                 dic.Add(2, "HiHi");
                 dic.Add(4, "HuHu1");
                 dic[4] = "HuHu"; // Save the data, overwrite it if the key exists, add it if it doesn't.
                 dic.Add(4, "HuHu"); // An exception will occur if it exists
                 var value= dic[4]; //There will be no exception when getting data.
                 var result = dic.ContainsKey(4); // Check whether it exists
                 foreach (var item in dic)
                 {
                     Console.WriteLine($"Key:{item.Key}, Value:{item.Value}");
                 }
                 //for (int i = 0; i < dic.Count; i++)
                 //{
                 // var value1 = dic[4];
                 // Console.WriteLine($"Key:{value1}, Value:{dic[i]}");
                 //}
                 // get value
                 //define
                 Dictionary dictExecutes = new Dictionary();

                 // add element
                 dictExecutes.Add("bmp", "paint.exe");
                 dictExecutes.Add("dib", "paint.exe");
                 dictExecutes.Add("rtf", "wordpad.exe");
                 dictExecutes.Add("txt", "notepad.exe");

                 // get value
                 Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

                 // change value
                 dictExecutes["rtf"] = "winword.exe";
                 Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

                 // Traverse KEY
                 foreach (string key in dictExecutes.Keys) Console.WriteLine("Key = {0}", key);

                 // Loop through VALUE
                 foreach (string item in dictExecutes.Values) Console.WriteLine("value = {0}", value);

                 // Traverse the dictionary
                 foreach (KeyValuePair kvp in dictExecutes)
                 {
                     Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                     if (kvp.Value == "paint.exe")
                         dictExecutes[kvp.Key] = "zhy.exe";
                 }
                    

                 //Add existing elements
                 try
                 {
                     dictExecutes.Add("txt", "winword.exe");
                 }
                 catch(ArgumentException)
                 {
                     Console.WriteLine("An element with Key = 'txt' already exists.");
                 }

                 // delete element
                 dictExecutes.Remove("doc"); // No exception
                 if (!dictExecutes.ContainsKey("doc")) Console.WriteLine("Key 'doc' is not found.");

                 // Determine if the key exists
                 if (dictExecutes.ContainsKey("bmp")) Console.WriteLine("An element with Key = 'bmp' exists.");
 

 

ConcurrentDictionary is a class in the .NET Framework that provides a thread-safe way to store key-value pairs. This means that multiple threads can access and modify ConcurrentDictionary simultaneously without causing data races or other concurrency issues.

Here are some basic usage examples:

 // Create a new ConcurrentDictionary instance
             var dictionary = new ConcurrentDictionary();

             //Add some elements to the dictionary
             dictionary.TryAdd("One", 1);
             dictionary.TryAdd("Two", 2);
             dictionary.TryAdd("Three", 3);

             //Try to get an element
             if (dictionary.ContainsKey("Two"))
             {
                 Console.WriteLine($"Value for 'Two': {dictionary["Two"]}");
             }
             else
             {
                 Console.WriteLine("Key 'Two' not found.");
             }

             //Try to modify an element
             dictionary["Two"] = 22;

             // Iterate through all elements in the dictionary
             foreach (var pair in dictionary)
             {
                 Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
             }

             //Delete an element
             int value;
             var sucdess = dictionary.TryRemove("Two",out value);
             if(sucdess)
             {
                 Console.WriteLine($"Removed key: {value}");
             }
             else
             {
                 Console.WriteLine("Key not found.");
             }
 

ConcurrentDictionary provides safer concurrent operations than ordinary Dictionary. OrdinaryDictionary may encounter data races and other concurrency issues in a multi-threaded environment because its internal implementation is not thread-safe. However, ConcurrentDictionary` is designed so that operations in a multi-threaded environment are thread-safe, and it uses an efficient concurrency control mechanism to protect its internal data structures.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/basic-use-of-c-dictionary-dictionary-and-thread-safe-dictionary/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索