Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the owner of a lock (Monitor)?

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.

like image 580
Timothy Pratley Avatar asked Feb 27 '11 18:02

Timothy Pratley


1 Answers

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.

like image 55
Hans Passant Avatar answered Sep 28 '22 08:09

Hans Passant