Why is this code not blocking?

I expect the following code to slow down when Clear tries to lock the same object that Build has already locked:

void Main()
{
    (new SiteMap()).Build();
}

class SiteMap
{
    private readonly object _lock = new object();

    public void Build()
    {
        lock (_lock)
        {
            Clear();

            Console.WriteLine("Build");
        }
    }

    public void Clear()
    {
        lock (_lock)
        {
            Console.WriteLine("Clear");
        }
    }
}

Conclusion:

Clear

Addition

Change 1

Thank you all for your answers.

If I add a Build call inside the Clear lock (keeping the rest of the code the same):

public void Clear()
{
    lock (_lock)
    {
        Build();

        Console.WriteLine("Clear");
    }
}

There is a dead end (or at least what I think LINQ Pad crashes).

According to your answers, this should not happen, because it is still the same thread.

Thank!

+5
source share
3 answers

In C #, a thread containing a lock can enter the same lock without locking.

The operator lock, as well as the monitor class on which it is built, is reentrant in .NET.


:

Build clear, - . , (, , StackOverflowException), Build Clear, Build, Clear ..

+8

lock :

, (), .

- "". , . , lock .

.

+5

I will not, because clear is called inside the same thread that has already applied the lock.

+4
source

All Articles