12

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,

theburningmonk
  • 15,701
  • 14
  • 61
  • 104

2 Answers2

15

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon, luckily we're not trying to use it, it's just something that popped into my head when I was reading through some articles on threading in C# :-P – theburningmonk Mar 09 '10 at 10:07
  • hi Jon, in C#4.5 this is now possible with [Monitor.IsEntered(Object obj)](http://msdn.microsoft.com/en-us/library/system.threading.monitor.isentered.aspx) right? – Ben Oct 06 '12 at 17:51
1

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.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317