Is there a way to discover what thread currently owns a lock? Specifically I am looking for some code to print out the thread that is preventing a lock from being taken. I want to try to lock for a given timeout, then report which thread is blocking the lock from being taken.
No. Just write the code:
private int lockOwner;
private object lockObject = new object();
...
void foo() {
lock(lockObject) {
lockOwner = Thread.CurrentThread.ManagedThreadId;
// etc..
}
}
There an otherwise undocumented way to get the lock owner, it isn't guaranteed to work but usually does. When you have a breakpoint active use Debug + Windows + Memory + Memory1. In the Address input box, type the name of the locking object ("lockObject") and press Enter. The address box changes to the address of the object in memory. Edit it and append "-4" to the address, press Enter. The first 4 bytes in the dump gives you the ManagedThreadId in hexadecimal. This works for 32-bit code, as long as you never called GetHashCode on the locking object. Which of course you shouldn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With