Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it better to lock(objLock) than lock(this) [duplicate]

Tags:

c#

locking

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?

like image 354
miguel Avatar asked May 21 '09 11:05

miguel


People also ask

Why should you avoid the lock keyword?

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.

What is lock this in C#?

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.


2 Answers

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.

like image 109
Winston Smith Avatar answered Oct 10 '22 05:10

Winston Smith


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();
like image 40
Steve Cooper Avatar answered Oct 10 '22 06:10

Steve Cooper