Why doesn't Lock'ing on same object cause a deadlock?

Eric picture Eric · Oct 22, 2012 · Viewed 12.2k times · Source

Possible Duplicate:
Re-entrant locks in C#

If I write some code like this:

class Program {
    static void Main(string[] args) {
        Foo();
        Console.ReadLine();
    }

    static void Foo() {
        lock(_lock) {
            Console.WriteLine("Foo");
            Bar();
        }
    }

    static void Bar() {
        lock(_lock) {
            Console.WriteLine("Bar");
        }
    }

    private static readonly object _lock = new object();
}

I get as output:

Foo
Bar

I expected this to deadlock, because Foo acquires a lock, and then waits for Bar to acquire the lock. But this doesn't happen.

Does the locking mechanism simply allow this because the code is executed on the same thread?

Answer

thumbmunkeys picture thumbmunkeys · Oct 22, 2012

For the same thread a lock is always reentrant, so the thread can lock an object as often as it wants.