tags:

views:

401

answers:

2

Possible Duplicates:
Why is lock(this) {...} bad?


In C# it is common to use lock(objLock) where objLock is an object created simply for the purpose of locking.

Why is this preferable to lock(this)? What are the negative implications of lock(this) other than taking a lock out on the class itself?

+13  A: 

Because something else could lock the instance, then you'd have a deadlock.

If you lock on the object you've created specifically for that purpose, you know you're in complete control, and nothing else is going to lock on it unexpectedly.

Winston Smith
Instance, not class.
Shog9
Sloppy of me. Duly edited.
Winston Smith
It's a feature, not a bug!what is another class wants to get exclusive access to specifically this instance?
Andy
+1  A: 

If you lock anything public, then both the class and some other class can try to get a lock. It's easy enough to create a sync object, and always preferrable;

private syncLock = new Object();
Steve Cooper