这是无锁TryGetValue()词典中的线程安全的?这是、线程、词典、安全

2023-09-03 13:01:09 作者:群英荟萃

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;
    }
}

问题答:是线程安全的?如果是,为什么?

Question a: Is it thread-safe? If yes, why?

问B:这是怎么回事双TryGetValue()模式名为

Question b: How is this double-TryGetValue() pattern called?

推荐答案

A)这是不是线程安全的,作为底层词典本身不是线程安全的。如果另一个线程调用加入的同时,不确定的行为可能会发生。

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)这实际上是在试图双重检查锁定。

b) This is effectively an attempt at double-checked locking.

我会推荐使用 ConcurrentDictionary 类代替,因为它的设计为这种情况。另一种选择是使用一个ReaderWriterLockSlim (或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.

 
精彩推荐
图片推荐