首页 > 编程语言 >c# Dictionary 字典与线程安全字典的基本使用

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

时间:2023-11-01 14:13:57浏览次数:42  
标签:dictExecutes Console Key Dictionary c# dic Add WriteLine 字典

在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`的设计使得在多线程环境下的操作是线程安全的,它使用了高效的并发控制机制来保护其内部数据结构。

标签:dictExecutes,Console,Key,Dictionary,c#,dic,Add,WriteLine,字典
From: https://www.cnblogs.com/wjygxjz/p/17802955.html

相关文章

  • VMware vCenter Server 8.0U2a 发布下载 - 集中式管理 vSphere 环境
    VMwarevCenterServer8.0U2a发布下载-集中式管理vSphere环境请访问原文链接:https://sysin.org/blog/vmware-vcenter-8-u2/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgVMwarevCenterServer是一款高级服务器管理软件,提供了一个集中式平台来控制vSphere......
  • Windows 11 version 23H2 中文版、英文版 (x64、ARM64) 下载 (released Oct 2023)
    Windows11version23H2中文版、英文版(x64、ARM64)下载(releasedOct2023)Windows11,version23H2,2023年10月31日发布请访问原文链接:https://sysin.org/blog/windows-11/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org全新Windows体验,让您与热爱的人......
  • CF484D Kindergarten
    CF484DKindergarten题目描述:有一组数,你要把他分成若干连续段。每一段的值,定义为这一段数中最大值与最小值的差。求一种分法,使得这若干段的值的和最大。数据范围:\(N<10^6\),\(a[i]<10^9\)。思路:仔细手摸几组数据,你会发现,我们将原序列分好后,每一段肯定是一个递增或者......
  • java使用ImageIO读取CMYK图片转存为RGB图片在本地和线上表现不同的问题
    项目里有jpg图片是CMYK颜色模式,需要转成RGB颜色模式,我使用的方法简单粗暴,就是利用ImageIO转存一下,在我的本地正常。但是丢到服务器上就有问题了,色差很大。不知道是什么情况。`BufferedImageimg=ImageIO.read(src);ImageIO.write(img,"jpeg",dest);`本......
  • Open Source DHCP proxy
    Thereareseveralopen-sourceprojects:DHCP-replayingithub https://github.com/topics/dhcp-relaySeems https://github.com/Mirantis/dhcp-relay looksgood. Anditis  Apache-2.0licensestartaDHCPproxyonahostgitclonehttps://github.c......
  • CodeWhisperer 初体验-手把手教导 给你飞一般的体验!
    文章作者:燛衣CodeWhisperer有以下几个主要用途:解决编程问题:CodeWhisperer可以帮助您解决遇到的编程问题。您可以描述您的问题或需求,CodeWhisperer将尽力提供相关的解决方案、代码示例或建议。无论您是遇到了语法错误、逻辑问题还是需要优化代码,CodeWhisperer都可以为您提......
  • longhorn storageclass 数据查看
    longhornstorageclass数据查看需要找到attach的机器进入目录chmod644-R/var/lib/kubelet/​/var/lib/kubelet/pods/{pod-id}/volumes/kubernetes.io~csi/{name}/mount如果已经Detached了.需要自己attach,然后然后进入对于的主机手动挂载device,然后访问需要挂载的设备......
  • 无涯教程-React Native - 路由
    在本章中,我们将了解ReactNative中的导航。步骤1-安装路由首先,我们需要安装Router路由,我们将在本章中使用ReactNativeRouterFlux,您可以在终端的项目文件夹中运行以下命令。npmireact-native-router-flux--save步骤2-应用代码由于我们希望Router处理整个应用程序......
  • Windows系统上禁用Jenkins跨站请求伪造(CSRF)保护功能
    禁用CSRF保护为了在Jenkins中禁用CSRF保护,请按照以下步骤操作:定位Jenkins服务在Windows搜索栏中输入services.msc,然后按Enter键打开服务。在服务列表中找到Jenkins服务。右键点击Jenkins服务,选择属性。修改Jenkins配置文件在Jenkins服务属性窗口中,找到路径到可执行......
  • 怎么用 CSS 美化被选中的文字?
    要使用CSS美化被选中的文字,可以使用::selection伪元素选择器来设置样式。该选择器会选中用户在页面上所选中的文本,因此您可以使用它来应用样式来改变文本的外观。例如,要将被选中的文本的背景色设置为黄色,可以使用以下CSS代码:::selection{background-color:yellow;......