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

Is there a way to find out which thread currently belongs to a lock? In particular, I'm looking for some code to print a stream that prevents blocking. I want to try to block a specific timeout, and then report which thread blocks the lock.

+6
multithreading c # monitor
source share
2 answers

Not. Just write the code:

private int lockOwner; private object lockObject = new object(); ... void foo() { lock(lockObject) { lockOwner = Thread.CurrentThread.ManagedThreadId; // etc.. } } 

Otherwise, an undocumented way to get the owner of the castle, it is not guaranteed to work, but usually does. When you use an active breakpoint, use Debug + Windows + Memory + Memory1. In the "Address" input field, enter the name of the lock object ("lockObject") and press "Enter". The address field changes to the address of the object in memory. Edit it and add "-4" to the address, press "Enter". The first 4 bytes in the dump give you ManagedThreadId in hexadecimal format. This works for 32-bit code if you never called GetHashCode on a lock object. Which, of course, should not.

+7
source share

EDITED:

FROM#:

  • Define thread execution blocking in C #

For C # you can get your answer here:

From Hans Passant ,

 class Test { private object locker = new object(); public void Run() { lock (locker) { // <== breakpoint here Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId); } } } 
+1
source share

All Articles