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

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

问题描述

我想emply,就算锁,如果图案来检查,如果对象是present在多线程环境的字典。因此,code我正在考虑看起来像这样:

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中存在的,不是吗?),而是将返回空值,所以我们进入保护区和重复检查。

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.

我的问题是我的假设是正确的和code是吧?

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

感谢。

修改

让我扔在一个限制。这本字典实际上是单一对象的字典。因此,一旦一个条目已被占用,它永远不会改变。就像一个单独的实例属性 - 一旦设置,它永远不会改变。鉴于约束,我们可以使用,如果锁定,如果模式?

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 )发挥,如果锁游戏,但字典是一类具有多种移动部件。阅读与写作必须始终同步,请参见这个MSDN网页

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天全站免登陆