c# - 字典查找是否需要锁定?

标签 c# multithreading dictionary locking lookup

lock(dictionaryX)
{
   dictionaryX.TryGetValue(key, out value);
}

在查找字典时是否需要锁定?

该程序是多线程的,同时向字典添加键/值。字典被锁定。

最佳答案

如前所述here :

Using TryGetValue() without locking is not safe. The dictionary is temporarily in a state that makes it unsuitable for reading while another thread is writing the dictionary. A dictionary will reorganize itself from time to time as the number of entries it contains grows. When you read at the exact time this re-organization takes place, you'll run the risk of finding the wrong value for the key when the buckets got updated but not yet the value entries.

更新: 查看 this page 的“线程安全”部分也是。

关于c# - 字典查找是否需要锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000347/

相关文章:

c# - 签署自动下载的exe

multithreading - 在 ColdFusion 中,为什么 Set & Forget 子线程不能访问 session /客户端范围?

java - ContainerRequestFilter 和 ContainerResponseFilter 线程安全吗?

python - 在 python 中从 CSV 文件创建字典

ios - Swift - 如何使用字典为 tableView 单元格提供文本?

ios - 在 map 标注气泡中加载远程图像时出现性能问题

C# 单元测试 : Retrieve Data from Repository

c# - 无法将自定义 .css 添加到嵌套的 ASP.NET 表格单元格控件

c# - 具有可变数量的 TextBlock(使用 ItemsControl 创建)的 WPF RichTextBox 失去选择行为

multithreading - 没有并发怎么能有并行呢?