这个非锁定的TryGetValue()字典是否可以访问线程安全? [英] Is this non-locked TryGetValue() dictionary access thread-safe?
问题描述
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:是它线程安全?如果是,为什么?
Question a: Is it thread-safe? If yes, why?
问题b:这种双重TryGetValue()模式是如何调用的?
Question b: How is this double-TryGetValue() pattern called?
推荐答案
a)这不是线程安全的,因为底层的 Dictionary
本身不是线程安全的。如果另一个线程同时调用Add,则可能会发生未定义的行为。
a) This is not thread-safe, as the underlying Dictionary
itself is not thread safe. If another thread is calling Add at the same time, undefined behavior can occur.
b)这实际上是在双重锁定。
我建议使用 ConcurrentDictionary 类,因为它是为这种情况设计的。另一个选择是使用 ReaderWriterLockSlim (或< a href =http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx =noreferrer> ReaderWriterLock ),如果您没有定位.NET 4.0 。
I would recommend using the ConcurrentDictionary class instead, as it's designed for this scenario. Another option would be to use a ReaderWriterLockSlim (or ReaderWriterLock), if you're not targetting .NET 4.0.
这篇关于这个非锁定的TryGetValue()字典是否可以访问线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!