Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have this code:

object o1 = new Object();
object o2 = o1;

Is obtaining a lock on o1 the same as obtaining a lock on o2? (If o1 is locked, will locking o2 block till o1 is released?)

like image 564
ytoledano Avatar asked Jan 05 '13 16:01

ytoledano


3 Answers

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.

like image 183
harold Avatar answered Sep 21 '22 19:09

harold


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.

like image 34
Henk Holterman Avatar answered Sep 23 '22 19:09

Henk Holterman


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

like image 39
usr Avatar answered Sep 19 '22 19:09

usr