确定持有锁的线程 [英] Identify the thread which holds the lock
问题描述
我的应用程序中的一个线程在以下lock语句处阻塞,并导致死锁
one of the threads in my application blocked at the following lock statement and resulted in a deadlock
void ExecuteCommand()
{
lock(this._lockinstance)
{
// do some operation
}
}
是否可以轻松地识别当前哪个线程正在持有该锁?..我的应用程序有50个以上的线程,这使得使用Visual Studio很难遍历每个调用堆栈来查找持有该锁的线程
Is it possible to easily identify which thread is currently holding the lock?.. My application has more than 50 threads, which makes it difficult to go through each callstack using visual studio to locate the thread that holds the lock
推荐答案
一些示例代码可以尝试:
Some sample code to try out:
class Test {
private object locker = new object();
public void Run() {
lock (locker) { // <== breakpoint here
Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
}
}
}
在指示的行上设置一个断点.中断时,使用Debug + Windows + Memory + Memory1.右键单击该窗口,然后选择"4字节整数".在地址框中,键入& locker.第二个单词是拥有锁的线程的线程ID.走过lock语句以查看其更改.
Set a breakpoint on the indicated line. When it breaks, use Debug + Windows + Memory + Memory 1. Right click the window and choose "4-byte Integer". In the Address box, type &locker. The 2nd word is the thread ID of the thread that owns the lock. Step past the lock statement to see it change.
请注意,该数字是托管线程ID,而不是您在调试+ Windows +线程"窗口中看到的操作系统线程ID.有点烂,您可能应该在程序中添加一些日志记录,以转储ManagedThreadId的值,以便您有一种将值与线程匹配的方法.更新:在更高的VS版本中已修复,调试> Windows>线程调试器"窗口现在显示ManagedThreadId.
Beware that the number is the managed thread ID, not the operating system thread ID that you see in the Debug + Windows + Threads window. That kinda sucks, you probably should add some logging to your program that dumps the value of ManagedThreadId so you have a way to match the value to a thread. Update: fixed in later VS versions, the Debug > Windows > Threads debugger window now shows the ManagedThreadId.
这篇关于确定持有锁的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!