9

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?)

H H
  • 263,252
  • 30
  • 330
  • 514
ytoledano
  • 3,003
  • 2
  • 24
  • 39

4 Answers4

12

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.

harold
  • 61,398
  • 6
  • 86
  • 164
7

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.

Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
2

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

usr
  • 168,620
  • 35
  • 240
  • 369
-1

Yes, .NET locks on references (Locking on a value type will result in an error)

Erix
  • 7,059
  • 2
  • 35
  • 61
  • It is indeed possible to lock on a value type, if it is boxed. It is a compile-time error to lock on an *expression* that evaluates to a value type. – Mike Zboray Jan 05 '13 at 22:00