Using lock on the key of a Dictionary

后端 未结 7 1068
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 17:18

I have a Dictionary.

EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references

7条回答
  •  一个人的身影
    2021-02-15 18:12

    Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the object, not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object.

    If you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe.

    However, try to stick to one rule - limit the visibility of the objects you lock on to the locking code itself whenever possible.

    That's why you see this:

    public class Something
    {
      private readonly object lockObj = new object();
    
      public SomethingReentrant()
      {
        lock(lockObj)    // Line A
        {
          // ...
         }
       }
    }
    

    rather than seeing line A above replaced by

      lock(this)
    

    That way, a separate object is locked on, and the visibility is limited.

    Edit Jon Skeet correctly observed that lockObj above should be readonly.

提交回复
热议问题