翼度科技»论坛 编程开发 .net 查看内容

c# Dictionary 字典与线程安全字典的基本使用

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
在C#中,字典(Dictionary)是一种特殊的集合,用于存储键/值对。这是一种关联数组,其中每个元素都包含一个键(Key)和一个值(Value)。
下面是一个简单的C#字典的例子:
  1. //字典:泛型;key - value,增删查改 都很快;
  2.                 // 字典如果数据量太大的话,也会影响效率.
  3.                 //  字典不是线程安全 ConcurrentDictionary
  4.                 Console.WriteLine("***************Dictionary******************");
  5.                 Dictionary<int, string> dic = new Dictionary<int, string>();
  6.                 dic.Add(1, "HaHa");
  7.                 dic.Add(5, "HoHo");
  8.                 dic.Add(3, "HeHe");
  9.                 dic.Add(2, "HiHi");
  10.                 dic.Add(4, "HuHu1");
  11.                 dic[4] = "HuHu"; // 保存数据,key有就覆盖 没有就新增
  12.                 dic.Add(4, "HuHu"); // 如果存在会异常
  13.                 var value= dic[4]; //获取数据 没有会异常的
  14.                 var result = dic.ContainsKey(4); // 检查是否存在
  15.                 foreach (var item in dic)
  16.                 {
  17.                     Console.WriteLine($"Key:{item.Key}, Value:{item.Value}");
  18.                 }
  19.                 //for (int i = 0; i < dic.Count; i++)
  20.                 //{
  21.                 //    var value1 = dic[4];
  22.                 //    Console.WriteLine($"Key:{value1}, Value:{dic[i]}");
  23.                 //}
  24.                 // 取值
  25.                 // 定义
  26.                 Dictionary<string, string> dictExecutes = new Dictionary<string, string>();
  27.                 // 添加元素
  28.                 dictExecutes.Add("bmp", "paint.exe");
  29.                 dictExecutes.Add("dib", "paint.exe");
  30.                 dictExecutes.Add("rtf", "wordpad.exe");
  31.                 dictExecutes.Add("txt", "notepad.exe");
  32.                 // 取值
  33.                 Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);
  34.                 // 改值
  35.                 dictExecutes["rtf"] = "winword.exe";
  36.                 Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);
  37.                 // 遍历 KEY
  38.                 foreach (string key in dictExecutes.Keys) Console.WriteLine("Key = {0}", key);
  39.                 // 遍历 VALUE
  40.                 foreach (string item in dictExecutes.Values) Console.WriteLine("value = {0}", value);
  41.                 // 遍历字典
  42.                 foreach (KeyValuePair<string, string> kvp in dictExecutes)
  43.                 {
  44.                     Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
  45.                     if (kvp.Value == "paint.exe")
  46.                         dictExecutes[kvp.Key] = "zhy.exe";
  47.                 }
  48.                     
  49.                 // 添加存在的元素
  50.                 try
  51.                 {
  52.                     dictExecutes.Add("txt", "winword.exe");
  53.                 }
  54.                 catch (ArgumentException)
  55.                 {
  56.                     Console.WriteLine("An element with Key = 'txt' already exists.");
  57.                 }
  58.                 // 删除元素
  59.                 dictExecutes.Remove("doc"); // 没有不会异常
  60.                 if (!dictExecutes.ContainsKey("doc")) Console.WriteLine("Key 'doc' is not found.");
  61.                 // 判断键存在
  62.                 if (dictExecutes.ContainsKey("bmp")) Console.WriteLine("An element with Key = 'bmp' exists.");
复制代码
  
ConcurrentDictionary是.NET框架中的一个类,它提供了一种线程安全的方式来存储键值对。这意味着多个线程可以同时访问和修改ConcurrentDictionary,而不会导致数据竞争或其他并发问题。
以下是一些基本的使用例子:
  1. // 创建一个新的 ConcurrentDictionary 实例
  2.             var dictionary = new ConcurrentDictionary<string, int>();
  3.             // 向字典中添加一些元素
  4.             dictionary.TryAdd("One", 1);
  5.             dictionary.TryAdd("Two", 2);
  6.             dictionary.TryAdd("Three", 3);
  7.             // 尝试获取一个元素
  8.             if (dictionary.ContainsKey("Two"))
  9.             {
  10.                 Console.WriteLine($"Value for 'Two': {dictionary["Two"]}");
  11.             }
  12.             else
  13.             {
  14.                 Console.WriteLine("Key 'Two' not found.");
  15.             }
  16.             // 尝试修改一个元素
  17.             dictionary["Two"] = 22;
  18.             // 遍历字典中的所有元素
  19.             foreach (var pair in dictionary)
  20.             {
  21.                 Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
  22.             }
  23.             // 删除一个元素
  24.             int value;
  25.             var sucdess = dictionary.TryRemove("Two", out value);
  26.             if (sucdess)
  27.             {
  28.                 Console.WriteLine($"Removed key: {value}");
  29.             }
  30.             else
  31.             {
  32.                 Console.WriteLine("Key not found.");
  33.             }
复制代码
  ConcurrentDictionary提供了比普通的Dictionary更安全的并发操作。普通的Dictionary在多线程环境下可能会遇到数据竞争和其他并发问题,因为它的内部实现并不是线程安全的。然而,ConcurrentDictionary`的设计使得在多线程环境下的操作是线程安全的,它使用了高效的并发控制机制来保护其内部数据结构。

来源:https://www.cnblogs.com/wjygxjz/archive/2023/11/01/17802955.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具