Recursive / nested locking in C# with the lock statement [duplicate]

混江龙づ霸主 提交于 2019-11-29 05:42:53

Yes, locks based on Monitor in .NET are recursive, and counted.

From the docs for Monitor.Enter:

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

Whether this is a good thing or not is up for debate...

Yes, Monitor support recursion, but you should be aware because this behavior differs from one synchronization primitive to another.

For example, ReaderWriterLockSlim by default doesn't support recursion and this code snippet throws exception:

public class MyClass
{
    ReaderWriterLockSlim rw = new ReaderWriterLockSlim();
    //You should explicitly stated that you want to use recursion
    ReaderWriterLockSlim rwWithRecursion = new ReaderWriterLockSlim (LockRecursionPolicy.SupportsRecursion);

    public void MethodA()
    {
        try {
           rw.EnterReadLock();
           // do something
           MethodB();
        }
        finally {
          rw.ExitReadLock();
        }
    }

    public void MethodB()
    {
        try {
           rw.EnterReadLock(); //throws LockRecursionException
        }
        finally {
          rw.ExitReadLock();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!