我使用锁来阻止代码段中的其他线程。但是,如果我有递归的情况,我想检测当前线程是否重新进入此部分以生成异常。如果递归,我不希望线程自锁死。我想通过调试错误消息停止程序。
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...
}
答案 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()节中检测线程是否可重入,并根据需要对其进行处理。
谢谢亚历克斯。