简体   繁体   English

添加项后,字典在ContainsKey上返回false

[英]Dictionary is returning false on ContainsKey after item is added

I have a dictionary declared as follows 我有一本字典声明如下

IDictionary<string, object> _objectIds = new Dictionary<string, object>();

I was experiencing some problems with it and it discovered that the instance returned false as a result of ContainsKey method and from the watch window I was sure that the item was there. 我遇到了一些问题,它发现该实例由于ContainsKey方法而返回false,并且从监视窗口中确定该项目在那里。 So I created helper method 所以我创建了辅助方法

private bool IdsContainsKey(string key)
{
  lock (syncObject)
  {
     lock (_objectIds)
     {
       if (_objectIds.ContainsKey(key))
         return true; // A
       if (_objectIds.ContainsKey(key))
         return true; // B
       return _objectIds.ContainsKey(key); // C
     }
  }
}

During my debugging session I run into situation when the method exited in place B and sometimes I made to C returning true. 在调试会话期间,我遇到了一种情况,该方法在B位置退出,有时我使C返回true。 Can anybody help me? 有谁能够帮助我? Thanks. 谢谢。

您需要确保在使用_objectIds每个位置上都加一个lock ,以确保正确同步。

Is there a reason for locking twice? 有两次锁定的理由吗? I think 我认为


private bool IdsContainsKey(string key)
{
  lock (syncObject)
  {
    ...
  }
}

should do it. 应该这样做。 Althought I read somewhere that it's never a good idea to lock the instance with itself. 尽管我在某处读到,锁定实例本身并不是一个好主意。

You don't need the lock(_objectIds) block. 您不需要lock(_objectIds)块。 Also, why are you using a wrapper dictionary? 另外,为什么要使用包装字典? Since you are using a generic Dictionary<TKey, TValue> , you should derive your own custom dictionary and implement your tracking there. 由于您使用的是通用Dictionary<TKey, TValue> ,因此您应该派生自己的自定义词典并在其中实现跟踪。 Finally, your code would be better written as: 最后,您的代码最好编写为:

private bool IdsContainsKey(string key) 
{ 
   lock (syncObject) 
   {
      return _objectIds.ContainsKey(key); 
   } 
}

The result of the method is going to be entirely dependent upon the value you pass in as key . 该方法的结果将完全取决于您作为key传递的值。 I suspect the problems you are encountering are due to incorrect locking in other places, an issue with your wrapper dictionary, or you aren't passing in the key you think you are. 我怀疑您遇到的问题是由于在其他地方的错误锁定,包装字典存在问题或您没有传递您认为的密钥而引起的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM