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

在C#中,字典(Dictionary)是一种特殊的集合,用于存储键/值对。这是一种关联数组,其中每个元素都包含一个键(Key)和一个值(Value)。

下面是一个简单的C#字典的例子:

//字典:泛型;key - value,增删查改 都很快;
                // 字典如果数据量太大的话,也会影响效率.
                //  字典不是线程安全 ConcurrentDictionary
                Console.WriteLine("***************Dictionary******************");
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(1, "HaHa");
                dic.Add(5, "HoHo");
                dic.Add(3, "HeHe");
                dic.Add(2, "HiHi");
                dic.Add(4, "HuHu1");
                dic[4] = "HuHu"; // 保存数据,key有就覆盖 没有就新增
                dic.Add(4, "HuHu"); // 如果存在会异常
                var value= dic[4]; //获取数据 没有会异常的
                var result = dic.ContainsKey(4); // 检查是否存在
                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]}");
                //}
                // 取值
                // 定义
                Dictionary<string, string> dictExecutes = new Dictionary<string, string>();

                // 添加元素
                dictExecutes.Add("bmp", "paint.exe");
                dictExecutes.Add("dib", "paint.exe");
                dictExecutes.Add("rtf", "wordpad.exe");
                dictExecutes.Add("txt", "notepad.exe");

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

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

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

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

                // 遍历字典
                foreach (KeyValuePair<string, string> kvp in dictExecutes) 
                {
                    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                    if (kvp.Value == "paint.exe")
                        dictExecutes[kvp.Key] = "zhy.exe";
                }
                    

                // 添加存在的元素
                try
                {
                    dictExecutes.Add("txt", "winword.exe");
                }
                catch (ArgumentException)
                {
                    Console.WriteLine("An element with Key = 'txt' already exists.");
                }

                // 删除元素
                dictExecutes.Remove("doc"); // 没有不会异常
                if (!dictExecutes.ContainsKey("doc")) Console.WriteLine("Key 'doc' is not found.");

                // 判断键存在
                if (dictExecutes.ContainsKey("bmp")) Console.WriteLine("An element with Key = 'bmp' exists.");

  

ConcurrentDictionary是.NET框架中的一个类,它提供了一种线程安全的方式来存储键值对。这意味着多个线程可以同时访问和修改ConcurrentDictionary,而不会导致数据竞争或其他并发问题。

以下是一些基本的使用例子:

 // 创建一个新的 ConcurrentDictionary 实例
            var dictionary = new ConcurrentDictionary<string, int>();

            // 向字典中添加一些元素
            dictionary.TryAdd("One", 1);
            dictionary.TryAdd("Two", 2);
            dictionary.TryAdd("Three", 3);

            // 尝试获取一个元素
            if (dictionary.ContainsKey("Two"))
            {
                Console.WriteLine($"Value for 'Two': {dictionary["Two"]}");
            }
            else
            {
                Console.WriteLine("Key 'Two' not found.");
            }

            // 尝试修改一个元素
            dictionary["Two"] = 22;

            // 遍历字典中的所有元素
            foreach (var pair in dictionary)
            {
                Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
            }

            // 删除一个元素
            int value;
            var sucdess = dictionary.TryRemove("Two", out value);
            if (sucdess)
            {
                Console.WriteLine($"Removed key: {value}");
            }
            else
            {
                Console.WriteLine("Key not found.");
            }

  ConcurrentDictionary提供了比普通的Dictionary更安全的并发操作。普通的Dictionary在多线程环境下可能会遇到数据竞争和其他并发问题,因为它的内部实现并不是线程安全的。然而,ConcurrentDictionary`的设计使得在多线程环境下的操作是线程安全的,它使用了高效的并发控制机制来保护其内部数据结构。

posted @ 2023-11-01 13:56  我家有个小鸡仔  阅读(740)  评论(0编辑  收藏  举报