c# - ContainsKey线程安全

标签 c# multithreading dictionary

在下面的代码中:

public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}

1) ContainsKey 线程安全吗? IOW,如果当另一个线程正在向字典中添加内容时该方法正在执行,会发生什么情况? 2) 第一次返回cache[key],有没有可能返回乱码?

TIA,

MB

最佳答案

ContainsKey 的内在线程安全性无关紧要,因为 ContainsKey 和缓存 [key] 之间没有同步。

例如:

if (cache.ContainsKey(key))
   // Switch to another thread, which deletes the key.
   return cache[key];

MSDN 在这一点上非常清楚:

To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

有关更多信息,JaredPar 在 http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx 上发布了一篇很棒的博客条目关于线程安全的集合。

关于c# - ContainsKey线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/710696/

相关文章:

c# - 为 Windows 编写的桌面应用程序可以在 Linux 上运行吗?

linux - Linux如何处理线程和进程调度

java - JTextArea 中正在执行写入操作

python - 在没有 NoneType 错误的情况下访问嵌套字典的 pythonic 方法是什么

c# - 使用 Unity 依赖注入(inject)注册 UrlHelper

c# - 我可以从 C# 类创建 VB 类的对象吗

C++ 常量安全

c++ - 无法链接到共享库

c++ - 这个函数只会被调用一次吗?

c# - 如何将应用程序服务注入(inject) AuthenticationHandler