How to test if a thread is holding a lock on an object in C#?

a 夏天 提交于 2019-12-06 18:45:14

问题


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.

Thanks,


回答1:


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.

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




回答2:


The relevant information is stored by the SyncBlock structure used by the CLR and can be viewed during debugging with e.g. WinDbg + sos. To my knowledge there is no way to obtain the information from managed code, but it may be possible from unsafe code assuming you can somehow (and in a reliable manner) obtain a pointer to the relevant data used by the CLR.



来源:https://stackoverflow.com/questions/2407943/how-to-test-if-a-thread-is-holding-a-lock-on-an-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!