你如何找到一个锁(监视器)的拥有者? [英] How do you find the owner of a lock (Monitor)?

查看:119
本文介绍了你如何找到一个锁(监视器)的拥有者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来发现什么线程当前拥有的锁? 具体来说,我在找一些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.

这篇关于你如何找到一个锁(监视器)的拥有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆