Nested misunderstanding blocking in C #?

Can someone explain to me why we need a nested lock?

look at this example:

lock (locker)
  lock (locker)
    lock (locker)
      {
        ...
      }

enter image description here

can someone explain (+ an example would be greatly appreciated).

+5
source share
4 answers

Can someone explain to me why we need a nested lock?

This is only a problem, because you may have nested (for example, mutually recursive) calls to methods that need to be blocked. These methods should allow calling with an already locked resource, but they cannot depend on it. So nested locking is allowed, not required.

The code you posted (and the book you are referencing) shows how it works, reducing it to an inline script. This is not real code.

, , , Enters .

+13

, .

, . , :

class A
{
    public void MethodOne()
    {
        using (locker)
        {
            ...body...
        }
    }

    public void MethodTwo()
    {
        using (locker)
        {
            ...body...
        }
    }
}

, MethodOne MethodTwo, MethodTwo, . locker.

, .NET. "", , () . , , MethodOne, MethodTwo. , .

, , , , . , .NET, ; , , .

+5

: . , , .

- , , . locker, "" .

.

, , Jirka Hanika, , , , - .

+2

, .

But it is worth noting that some locks may be nested. Check the ReaderWriterLockSlim class, which you enter as a read lock, and then inside this area, you can update it to write lock.

EDIT: As Royi Namir points out, invoking nested functions, each with its own lock, will conceptually create the above scenario, but as the question is asked, it seems like 3 locks are executed in the same volume, one after the other, which makes less meaning.

+1
source

All Articles