导读:本期聚焦于小伙伴创作的《C# ConcurrentDictionary怎么用才能实现线程安全的字典操作》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C# ConcurrentDictionary怎么用才能实现线程安全的字典操作》有用,将其分享出去将是对创作者最好的鼓励。

在C#多线程开发中,如果多个线程同时读写同一个Dictionary实例,很容易抛出InvalidOperationException或者产生数据不一致。ConcurrentDictionary位于System.Collections.Concurrent命名空间,是专为高并发场景设计的线程安全字典,内部通过分段锁等机制减少阻塞。

C# ConcurrentDictionary怎么用才能实现线程安全的字典操作

基本初始化与添加

使用ConcurrentDictionary时,最常见的操作是线程安全地添加元素。相比Dictionary的Add方法,它提供了TryAdd来避免重复键异常。

using System;
using System.Collections.Concurrent;

class Program
{
    static void Main()
    {
        ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>();
        bool added = dict.TryAdd("apple", 1);
        Console.WriteLine(added); // True
        added = dict.TryAdd("apple", 2);
        Console.WriteLine(added); // False,键已存在
    }
}

获取或添加

当我们需要缓存数据时,经常需要“如果不存在就添加,存在就返回”的原子操作,这时可以使用GetOrAdd。

using System;
using System.Collections.Concurrent;

class Program
{
    static void Main()
    {
        ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>();
        int value = dict.GetOrAdd("count", 100);
        Console.WriteLine(value); // 100
        value = dict.GetOrAdd("count", 200);
        Console.WriteLine(value); // 100,不会覆盖
    }
}

更新已存在的键

AddOrUpdate允许我们根据旧值计算新值,在计数器场景中非常实用。

using System;
using System.Collections.Concurrent;

class Program
{
    static void Main()
    {
        ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>();
        dict.TryAdd("hit", 0);
        int result = dict.AddOrUpdate("hit", 1, (key, old) => old + 1);
        Console.WriteLine(result); // 1
        result = dict.AddOrUpdate("hit", 1, (key, old) => old + 1);
        Console.WriteLine(result); // 2
    }
}

删除与遍历

ConcurrentDictionary同样支持TryRemove,并且在遍历时不会因其他线程修改而抛异常。

using System;
using System.Collections.Concurrent;

class Program
{
    static void Main()
    {
        ConcurrentDictionary<string, int> dict = new ConcurrentDictionary<string, int>();
        dict.TryAdd("a", 1);
        dict.TryAdd("b", 2);
        if (dict.TryRemove("a", out int removed))
        {
            Console.WriteLine(removed);
        }
        foreach (var item in dict)
        {
            Console.WriteLine(item.Key + ":" + item.Value);
        }
    }
}

方法对比

方法作用是否原子
TryAdd键不存在时添加
GetOrAdd获取或添加默认值
AddOrUpdate更新已有键值
TryRemove移除指定键

在多数业务代码中,优先使用上述原子方法,可以减少手动lock带来的死锁风险和性能损耗。如果操作非常复杂且必须多步完成,再考虑使用传统锁方案。

C#ConcurrentDictionary线程安全修改时间:2026-07-31 06:21:09

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。