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:线程安全吗?如果是,为什么?这个非锁定TryGetValue()字典访问线程安全吗?
问题b:这个double-TryGetValue()模式是如何调用的?
旁注;对于'Hashtable',双重检查锁定*的模式显然是安全的。字典的安全性不太清楚。 –