Reputation: 10838
Lets say we want to achieve thread synchronization and we use lock for this. But if a question is asked is the lock on the object or on the reference, How do we answer this question?
private static readonly object doSomethingLock = new object();
public static void DoSomething (SomeObject o)
{
lock(doSomethingLock)
{
o.Update();
// etc....
}
}
Upvotes: 0
Views: 122
Reputation: 137188
That lock is on the use of that object in that static method, not on the object globally.
If another thread tries to call that method it will be blocked until the first thread completes it's call.
It won't stop some other method accessing that object elsewhere in your code, but as long as the only access to the object is inside the lock then it's equivalent to locking the object.
Upvotes: 2
Reputation: 8551
The lock is on the object. Your code is equivalent to this code:
private static readonly object doSomethingLock = new object();
public static void DoSomething (SomeObject o)
{
var sameObject = doSomethingLock;
lock(sameObject)
{
o.Update();
// etc....
}
}
Upvotes: 5