Detecting deadlocks in a C# application

Jon Tackabury picture Jon Tackabury · Feb 3, 2009 · Viewed 26.5k times · Source

Possible Duplicate:
C#/.NET analysis tool to find race conditions/deadlocks

I am debugging an application that I suspect is getting deadlocked and hanging. However, this only occurs every few days, and it never happens on my computer so I can't hook a debugger up to it. Are there any utilities or methods I can use to query the running application and find out what methods/locks/whatever it is deadlocked on?

Update: Typically the application is running at a customer location and I don't have access to the machine, and I'm not entirely comfortable asking them to install tons of software.

Answer

Brian Rasmussen picture Brian Rasmussen · Feb 3, 2009

You can use WinDbg to inspect the threads in the application. Here's a brief plan of what you could do.

  • When the application hangs, copy the WinDbg files to the machine.
  • Either attach WinDbg to the process or use ADPlus to get a hang dump of the process. If you choose ADPlus, you then load the dump in WinDbg.
  • From WinDbg you load sos.dll, so you can inspect managed code.
  • The !threads command will show you all threads in the application and the !clrstack command, will show you what they are doing. Use ~e!clrstack to dump the call stack of all threads. Look for calls to Wait methods as they indicate locking.
  • The !syncblk command will give you information of what threads are holding the different locks.
  • To find out what lock a given thread is trying to acquire, switch to the thread and inspect stack objects (!dso). From here you should be able to find the lock the thread is trying to acquire.

Clarification: WinDbg doesn't require a regular install. Just copy the files. Also, if you take the hang dump, you can continue debugging on another machine if so desired.

Addition: Sosex has the !dlk command that automatically identifies deadlocks in many situations. It doesn't work all the time, but when it does, it does all the work for you, so that should be your first choice.