在多线程环境中访问.NET字典 [英] Accessing .NET dictionary in a multithreaded environment

查看:262
本文介绍了在多线程环境中访问.NET字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用if-lock-if模式来检查一个对象是否存在于多线程环境中的字典中。所以,我正在考虑的代码如下所示:

I would like to emply the if-lock-if pattern for checking if an object is present in the dictionary in a multithreaded environment. So, the code I am considering looks like so:

private IDictionary<string, SomeType> m_dic = new Dictionary<string, SomeType>();

private SomeType GetSomeObject(string key)
{
  SomeType obj;
  if (!m_dic.TryGetValue(key, out obj))
  {
    lock(m_dic)
    {
      if (!m_dic.TryGetValue(key, out obj))
      {
        m_dic[key] = obj = CreateSomeObject(key);
      }
    }
  }
  return obj;
}

我的假设是,即使另一个线程将对象插入到相同的键现在,TryGetValue将不会返回部分设置的引用(这样的东西不存在于.NET中,是吗?),而是返回null,所以我们进入保护部分并重复检查。

I act on the assumption that even if another thread is inserting the object at the same key right now, the TryGetValue will not return a partially set reference (such thing does not exist in .NET, does it?), rather it will return null and so we enter the protected section and repeat the check.

我的问题是我的假设正确,代码是正确的吗?

My question is my assumption correct and the code is right?

谢谢。

编辑

让我放一个限制。字典实际上是单身对象的字典。所以,一旦入口被占用,它永远不会改变。就像单身的Instance属性一旦设置,它永远不会改变。给定这个约束,我们可以使用if-lock-if模式吗?

Let me throw in a restriction. The dictionary is actually a dictionary of singleton objects. So, once an entry is occupied, it is never changed. Just like the Instance property of a singleton - once it is set, it is never changed. Given that constraint, can we use the if-lock-if pattern?

推荐答案

为了清楚起见,编辑

不,这是一个非常糟糕的想法。您可以在简单和原子( int )上播放if-lock游戏,但是Dictionary是具有多个移动部分的类。阅读和写作必须始终同步,请参阅此MSDN页面上的ThreadSafety部分

No this is a very bad idea. You can play an if-lock game on something simple and atomic (an int) but a Dictionary is a class with multiple moving parts. Reading and Writing must be synchronized at all times, See the ThreadSafety section on this MSDN page.

这篇关于在多线程环境中访问.NET字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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