C# Dictionary 线程安全指南:多线程下操作 Dictionary<string, DateTime> 的加锁策略

在讲述这个之前,我们先要弄清楚

为什么需要加锁

竞态条件示例

cs 复制代码
// 以下操作在多线程中都需要保护:
Dictionary<string, DateTime> dict = new Dictionary<string, DateTime>();

// 线程A
if (!dict.ContainsKey("ip1"))  // 检查不存在

// 此时线程B也检查同一个key,也不存在

// 线程A
dict.Add("ip1", time);  // 成功添加

// 线程B
dict.Add("ip1", time);  // 异常!键已存在

在C#中,当你在操作Dictionary<string, DateTime>这样的集合时,是否会加锁主要取决于你使用的是哪种类型的Dictionary。在.NET框架中,有两种主要的Dictionary实现:

  1. ‌**System.Collections.Generic.Dictionary<TKey, TValue>** ‌:这是非线程安全的。这意味着如果你在多线程环境下同时对同一个Dictionary实例进行写操作(如添加、删除、修改元素),你需要自己手动管理线程安全。

  2. ‌**System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>** ‌:这是线程安全的。ConcurrentDictionary<TKey, TValue>提供了内置的线程安全机制,允许多个线程同时访问和修改集合而不需要额外的锁。

如果你使用的是System.Collections.Generic.Dictionary<TKey, TValue>

如果你决定使用普通的Dictionary,并且需要在多线程环境下安全地操作它,你有以下几种选择:

新手可能认为 Mutex 更"强大"

cs 复制代码
public readonly static Mutex mutex = new Mutex(); // 其实过重
而有经验的开发者会用:
cs 复制代码
private static readonly object _lockObj = new object();
lock(_lockObj) { ... }

Mutexlock 更重量级:

  • Mutex:内核级对象,上下文切换开销大

  • lock:用户态同步,性能更好

cs 复制代码
public static Dictionary<string, DateTime> RemoteLinkStatue = new Dictionary<string, DateTime>();

/// <summary>
/// 读取操作加锁,跨线程
/// </summary>
public readonly static Mutex readRemoteLinkStatueMutex = new Mutex();

App.readRemoteLinkStatueMutex.WaitOne();
try 
{
    if (App.RemoteLinkStatue.ContainsKey(remoteIp)) 
        App.RemoteLinkStatue[remoteIp] = DateTime.Now;
    else 
        App.RemoteLinkStatue.Add(remoteIp, DateTime.Now);
}
finally 
{
    App.readRemoteLinkStatueMutex.ReleaseMutex();
}

更好的替代方案

方案1:使用 lock(推荐)

你可以使用lock语句来确保对字典的访问是线程安全的。例如:

cs 复制代码
private static readonly object _dictionaryLock = new object();

lock(_dictionaryLock) 
{
    if (App.RemoteLinkStatue.ContainsKey(remoteIp)) 
        App.RemoteLinkStatue[remoteIp] = DateTime.Now;
    else 
        App.RemoteLinkStatue.Add(remoteIp, DateTime.Now);
}
方案2:使用 ConcurrentDictionary(最佳)

使用ConcurrentDictionary<TKey, TValue> ‌:如果你经常需要在多线程环境中使用字典,并且对性能有较高要求,可以考虑使用ConcurrentDictionary

cs 复制代码
private static ConcurrentDictionary<string, DateTime> _myConcurrentDictionary = new ConcurrentDictionary<string, DateTime>();

public void AddItem(string key, DateTime value)
{
    // 无需手动加锁,方法本身是原子的、线程安全的
    _myConcurrentDictionary.TryAdd(key, value);
}

// 原子性操作
RemoteLinkStatus.AddOrUpdate(remoteIp, DateTime.Now, (key, oldValue) => DateTime.Now);

总结**:**

对于纯跨线程的场景,使用 Mutex过度设计

  • 单线程环境或只读访问 -> 使用 Dictionary,无需锁。

  • 如果你的应用是多线程的,并且对性能有较高要求,推荐使用ConcurrentDictionary<TKey, TValue>

  • 如果出于某种原因你不得不使用普通的Dictionary<TKey, TValue>,确保通过适当的同步机制(如锁)来保护对字典的访问。

选择合适的集合类型和同步策略对于确保应用程序的稳定性和性能至关重要

相关推荐
俊基科技7 分钟前
清晰通信,守护矿场安全——A-29 回音消除模块在矿山矿井通信系统中的应用
安全·ai降噪·语音模块·回音消除·矿场通讯·矿场安全
2601_963749101 小时前
越华环保集团数字化污水治理:端边云采集架构与平台对接实现
java·大数据·架构
xcLeigh1 小时前
Go入门:整数类型的溢出与安全边界
java·安全·golang
源码宝2 小时前
SpringBoot+Vue2 诊所门诊管理系统,完整前后端源码,可直接部署上线
java·源码·his系统·门诊系统·程序代码·诊所系统·门诊his
yychen_java2 小时前
九:Text-to-SQL 智能数据查询与 Human-in-the-Loop 人机协作
java·人工智能·架构
ai小陈2 小时前
FramePack图生视频云端部署实战:从单图输入到视频输出的完整流程
服务器·人工智能·安全·ai·音视频·gpu算力
lhldsg3 小时前
智慧场馆解决方案小程序开发实战:从架构设计到部署指南
java·小程序·uni-app
Freak嵌入式3 小时前
Pico UART 数据收发实战:硬件配置、MicroPython 编程
java·开发语言·单片机·嵌入式硬件·生活
2401_868534784 小时前
第7章 网络环境规划:综合篇考点梳理
网络·安全
devilnumber4 小时前
Oracle 与 MySQL substr 函数差异总结
java·数据库·mysql·oracle