你如何找到一个锁(监视器)的拥有者?监视器

由网友(妻奴)分享简介:有没有办法来发现什么线程当前拥有的锁?具体来说,我在找一些code打印出是preventing被采取了锁的线程。我想尝试锁定一个给定的超时,然后报告该线程被阻塞被采取了锁。Is there a way to discover what thread currently owns a lock?Specifical...

有没有办法来发现什么线程当前拥有的锁? 具体来说,我在找一些code打印出是preventing被采取了锁的线程。我想尝试锁定一个给定的超时,然后报告该线程被阻塞被采取了锁。

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.

推荐答案

没有。只写了code:

No. Just write the code:

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

有一个原本无证的方式来获得锁的拥有者,它不能保证工作,但通常不会。当你有一个断点,积极利用调试+的Windows +内存+内存1。在地址输入框中,键入锁定对象(lockObject)和preSS输入的名称。地址框更改为内存中的对象的地址。编辑并追加-4的地址,preSS输入。垃圾堆里的前4个字节为您提供了十六进制的ManagedThreadId。这适用于32位code,只要你从来没有所谓的锁定对象GetHash code。当然,你不应该。

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.

阅读全文

相关推荐

最新文章