Altough I am using locks in my app, I do not understand what exactly does locking on particular reference type. I thought it just stops the thread until the content of {} is finished. But I have read that locking(this) is bad, if its public – why? The article explained it but I do not understand sice I do not know what happened to the object itself being locked.
For example, what if I use lock(this) and from another thread call its method? I thought only the code under the lock is protected, or I will be unable to access the locked object at all?
Thanks
Altough I am using locks in my app, I do not understand what exactly
Share
Each object on the managed heap can be used as a lock-object, which is a means to synchronize access between threads.
Well, a
lockit stops other threads from acquiring the lock until the lock is released, which is most commonly at the end of alockstatement (but it could also be aMonitor.Wait).The
lock(this)usage is dangerous because locking is complex, and understanding exactly which threads are locking which object(s) at which time is very important to avoid deadlocks; however, if youlock(this)you aren’t in control of other threads – which could also be (unexpectedly) locking the same object. It is far safer to use aprivatefield for locking.As an example, if you have (in a synchronized list):
Then it isn’t hard to imagine another bit of code also having a reference to this synchronized list, and locking on it, for example:
Which is a potential deadlock; it would be much better if
Countdidn’tlock(this), but locked a private object, i.e.Now there is no risk of this issue. Another issue here is that both field-like events and
[MethodImpl]causelock(this). Locking on aType(for static methods) is equally dangerous for exactly the same reasons.