Dictionary在多线程写入时 TryGetValue 安全吗?
不安全。当其他线程正在向字典中写入数据(如添加、删除或修改键值对)时,调用 trygetvalue 可能会抛出 invalidoperationexception,或者返回错误的结果。这是因为 system.collections.generic.dictionary 不是线程安全的集合类,其内部数据结构(哈希表)在并发读写时会发生状态不一致。

如何验证 TryGetValue 的崩溃行为?
可以通过编写一个包含两个线程的 C# 控制台程序来验证:一个线程持续执行 Add 操作,另一个线程持续执行 TryGetValue 查询。运行该程序通常会迅速触发异常。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var dict = new Dictionary<string int>();
var tasks = new Task[2];
// 线程1:不断写入
tasks[0] = Task.Run(() =>
{
for (int i = 0; i
{
try
{
while (true)
{
int value;
bool found = dict.TryGetValue("key_500", out value);
if (!found) { /* 忽略未找到 */ }
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught: {ex.GetType().Name}");
}
});
Task.WaitAll(tasks);
}
}</string>
预期结果:控制台输出 Caught: InvalidOperationException。这证实了 TryGetValue 在并发写入环境下是不安全的。

使用 ConcurrentDictionary 替代方案的效果
将上述代码中的 Dictionary 替换为 ConcurrentDictionary,可以解决线程安全问题。ConcurrentDictionary 专为多线程环境设计,其 TryGetValue 方法保证在并发读写时的安全性,不会抛出异常,且能获取到一致的数据视图。
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var dict = new ConcurrentDictionary<string int>();
var tasks = new Task[2];
// 线程1:不断写入
tasks[0] = Task.Run(() =>
{
for (int i = 0; i
{
try
{
while (true)
{
int value;
bool found = dict.TryGetValue("key_500", out value);
if (!found) { /* 忽略未找到 */ }
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught: {ex.GetType().Name}");
}
});
Task.WaitAll(tasks);
Console.WriteLine("Completed successfully without exceptions.");
}
}</string>
预期结果:程序正常运行并输出 Completed successfully without exceptions.,无异常抛出。












