How to use Multiple Variables for a lock Scope in C#

Shamim Hafiz picture Shamim Hafiz · May 20, 2010 · Viewed 8k times · Source

I have a situation where a block of code should be executed only if two locker objects are free.

I was hoping there would be something like:

lock(a,b)
{
    // this scope is in critical region
} 

However, there seems to be nothing like that. So does it mean the only way for doing this is:

lock(a)
{
    lock(b)
    {
        // this scope is in critical region
    }
}

Will this even work as expected? Although the code compiles, but I am not sure whether it would achieve what I am expecting it to.

Answer

dtb picture dtb · May 20, 2010
lock(a) lock(b) { // this scope is in critical region }

This could would block until the thread can acquire the lock for a. Then, with that lock acquired, it would block until the thread can acquire the lock for b. So this works as expected.

However, you have to be careful not to do this somewhere else:

lock(b) lock(a) { // this scope is in critical region }

This could lead to a deadlock situation in which thread 1 has acquired the lock for a and is waiting to acquire the lock for b, and thread 2 has acquired the lock for b and is waiting to acquire the lock for a.