Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to pass to the lock keyword?

Tags:

c#

.net

locking

What is the difference (if any) between using

void MethodName()
{
    lock(this)
    {
        // (...)
    }
}

or

private object o = new object();
void MethodName()
{
    lock(o)
    {
        // (...)
    }
}

?

Is there a difference in performance? Style? Behaviour?

like image 307
juan Avatar asked Feb 23 '10 15:02

juan


People also ask

When would you use the lock keyword?

The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.

What is the use of lock keyword 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.

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.

Is lock thread safe C#?

No, it's not thread safe. Add and Count may be executed at the "same" time. You have two different lock objects.


1 Answers

lock(this) will lock on the "current" object.

Locking on "this" is usually a bad idea as it exposes the lock to other code; I prefer to have a readonly field, like this:

public class Foo
{
    private readonly object padlock = new object();

    public void SomeMethod()
    {
        lock(padlock)
        {
            ...
        }
    }
}

That way all calls to SomeMethod (and anything else in Foo which locks on padlock) will lock on the same monitor for the same instance of Foo, but nothing else can interfere by locking on that monitor.

In reality, unless you're dealing with "rogue" code, it's unlikely that other code will actually lock on the reference to an instance of Foo, but it's a matter of encapsulation.

like image 76
Jon Skeet Avatar answered Sep 30 '22 06:09

Jon Skeet