有没有一种方法可以获取锁的递归级别#

Is there a method to get recursion level of lock c#

我在我的一段代码中使用锁来阻止其他线程。但是我想检测一下如果我有递归的情况,当前线程是否重新进入这个section会产生异常。如果它是递归的,我不希望线程自死锁。我想用调试错误消息停止程序。

lock (x)
{
    if (getlLockLevel(x) > 1)   // Do not work, is the method I want to know
    {
        throw new Exception("ERROR : Current thread is recursive");
    }

    // My code...

}

我根据 Alex K. 的建议修改了我的代码如下:

if (Monitor.IsEntered(x)   // That's what I want to check
{
    throw new Exception("ERROR : Current thread is reentrant");
}

lock (x)
{
    // My code...

}

我现在可以检测线程是否可重入 lock() 部分并根据需要进行处理。

谢谢亚历克斯。