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

时间:2019-01-17 13:33:28

标签: c# recursion locking

我使用锁来阻止代码段中的其他线程。但是,如果我有递归的情况,我想检测当前线程是否重新进入此部分以生成异常。如果递归,我不希望线程自锁死。我想通过调试错误消息停止程序。

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...

}

1 个答案:

答案 0 :(得分:1)

我根据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()节中检测线程是否可重入,并根据需要对其进行处理。

谢谢亚历克斯。

相关问题