如何测试如果一个线程在C#中的对象上持有锁?线程、对象、测试

2023-09-03 15:49:57 作者:傲天~皇家师

有没有一种方法来测试,如果当前线程的对象上保持监视器锁?即相当于Java中的Thread.holdsLock。

Is there a way to test if the current thread is holding a monitor lock on an object? I.e. an equivalent to the Thread.holdsLock in Java.

谢谢

推荐答案

我不相信有。有难看黑客的事情你可以做喜欢叫 Monitor.Wait(显示器,0)和追赶的 SynchronizationLockException ,但这是pretty的可怕(和理论上可以捕获了另一个线程在等待脉冲)。

I don't believe there is. There are grotty hack things you could do like calling Monitor.Wait(monitor, 0) and catching the SynchronizationLockException, but that's pretty horrible (and could theoretically "catch" a pulse that another thread was waiting for).

我建议你尝试重新设计,这样你就不需要这个,我害怕。

I suggest you try to redesign so that you don't need this, I'm afraid.

编辑:在.NET 4.5,这是可用的Monitor.IsEntered.

In .NET 4.5, this is available with Monitor.IsEntered.

 
精彩推荐
图片推荐