开发者

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. So I created helper m开发者_JAVA技巧ethod

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. Can anybody help me? Thanks.


You need to make sure you put a lock around every place you use _objectIds in order to be sure you are synchronizing properly.


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. 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. 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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜