Why does the lock object have to be readonly?

后端 未结 4 1916
渐次进展
渐次进展 2020-12-29 22:29

When implementing a lock, I used to create a private object inside of my class:

If I want to be sure that it is locked in the thread that created my class:



        
4条回答
  •  长情又很酷
    2020-12-29 23:05

    I guess what meant is "a variable referencing a lock object should be read only".

    You lock on a lock object that variable references, not on a variable itself. I.e. having

    private object Locker = new object();
    

    you lock on that new object(), not on Locker field. Then, if you replace the value of the field with a reference to another object, say

    Locker = new object();
    

    and lock on it, you are locking on two different objects, and that defeats the purpose of the locking, because you do not get a synchronized access now.

提交回复
热议问题