【发布时间】:2019-05-28 15:13:20
【问题描述】:
我在多线程环境中有一个 c# 字典。我正在使用 TryGetValue 进行无锁阅读,同时字典正在重组。是否有可能获得与此键无关的完全不同的值?我的意思不仅仅是一个不是最新的值,而是一个完全错误的值,对应于不同的键。
public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict,
TKey oldKey, TKey newKey)
{
TValue value;
if (!dict.TryGetValue(oldKey, out value))
return false;
dict.Remove(oldKey); // do not change order
dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort
return true;
}
【问题讨论】:
-
您使用的是什么实现方式?如果是
System.Collections.Generic.Dictionary<TKey, TValue>,那么不,你不能在没有锁定的情况下在线程之间安全地使用它。 -
谢谢老哥,问题解决了...你能告诉我如何关闭或删除这个帖子吗??
-
您无法关闭问题,但您可以接受答案或删除问题。
标签: multithreading c#-4.0 .net-4.0