Locking in .Net - is the reference locked or the object? Locking in .Net - is the reference locked or the object? multithreading multithreading

Locking in .Net - is the reference locked or the object?


If it locked the reference itself, locking would be profoundly useless. The problem is, references themselves are copied by value, so you'd always be locking some temporary copy that gets thrown away immediately.

So that's not how it works. The lock is obtained on the instance that the reference references, not the reference itself.


Is obtaining a lock on o1 the same as obtaining a lock on o2?

Yes.

It works with something called a sync-block that is part of every object instance. But functionally you can think of it as using the object as a key in a Dictionary.

Locking on the reference would be the same as locking on a Value type, with the same problems.


Yes, because a lock is taken on an object, not on a object reference. o2 = o1 copies the reference, not the object.