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

.net, c#, locking, multithreading

Solution

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

Problem

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,

Original source