2

My application is in a deadlock. Is there any ways to identify the objects which are presently locked (as shown below)?


void DoWork()
{
   lock(this._lockObj)
   {
      // Do some work
   }
}
Maanu
  • 5,093
  • 11
  • 59
  • 82
  • If it helps, you can use `Monitor.TryEnter` to evaluate whether a single specific object is locked. – mqp Aug 20 '10 at 15:15
  • dupe? http://stackoverflow.com/questions/1300199/c-anyway-to-detect-if-an-object-is-locked – Tim Coker Aug 20 '10 at 15:16
  • possible duplicate of [Identify the thread which holds the lock](http://stackoverflow.com/questions/3523544/identify-the-thread-which-holds-the-lock) – Hans Passant Aug 20 '10 at 15:17
  • 1
    @mquander `TryEnter` tells you if an object **was** locked not if it **is** locked. – JaredPar Aug 20 '10 at 15:25
  • Well, it tells you whether it was locked at the moment that you called `TryEnter` -- I must be missing the distinction you're drawing. I agree that it's probably not going to help a lot; I just mentioned it in case the OP wasn't aware of it. – mqp Aug 20 '10 at 16:37
  • @mquander but what can you do with that value (other than logging)? Any action you take because of that value is fundamentally flawed and subject to race conditions – JaredPar Aug 20 '10 at 16:50
  • Since the OP is debugging a problem, it seems like a tool for simply inspecting and/or logging the state of the system might be useful for him. Perhaps he has some idea about in what circumstances the object might be getting locked, and he can test it to see if he's right. – mqp Aug 20 '10 at 18:10

2 Answers2

7

The best way to do this is to use WinDbg and the SOS extension. It has a command named !SyncBlk that provides just this information. Here is a link to a quick tutorial

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
4

If you're debugging under Visual Studio, it's not too hard. You'll need two debug windows in particular: Call stack and Threads. Pause the program, and then in the thread window double click on each thread, to find where it's currently stopped. The deadlocking threads should have their execution stopped on a "lock" statement.

Then, on each of the deadlocked threads, you can trace your way up the stack to find the other lock. Just double click each method on the call and look at the context until you find another lock that you're inside of.

Bryce Wagner
  • 2,640
  • 1
  • 26
  • 43