这是无锁TryGetValue()词典中的线程安全的? [英] Is this non-locked TryGetValue() dictionary access thread-safe?

查看:397
本文介绍了这是无锁TryGetValue()词典中的线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 类代替,因为它的设计为这种情况。另一种选择是使用一个<一href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx">ReaderWriterLockSlim (或<一href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx">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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆