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

柔情痞子 提交于 2019-12-08 16:45:46

问题


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.


回答1:


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.




回答2:


EDITED :

C# :

  • Identify thread holding lock 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);
        }
    }
}


来源:https://stackoverflow.com/questions/5135013/how-do-you-find-the-owner-of-a-lock-monitor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!