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?
Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.
The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With