【发布时间】:2011-10-07 23:50:41
【问题描述】:
private object lockObj = new object();
private Dictionary<int, string> dict = new Dictionary<int, string>();
public string GetOrAddFromDict(int key)
{
string value;
// non-locked access:
if (dict.TryGetValue(key, out value))
return value;
lock (this.lockObj)
{
if (dict.TryGetValue(key, out value))
return value;
string newValue = "value of " + key; // place long operation here
dict.Add(key, newValue);
return newValue;
}
}
问题a:它是线程安全的吗?如果是,为什么?
问题 b:这种双 TryGetValue() 模式是如何调用的?
【问题讨论】:
-
旁注;对于
Hashtable,这种双重检查锁定模式是明确安全的。这对字典是否安全尚不清楚。
标签: c# .net multithreading dictionary thread-safety