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',雙重檢查鎖定*的模式顯然是安全的。字典的安全性不太清楚。 –