Mike Pateras
Mike Pateras

Reputation: 15015

How can I find out which thread has the lock on a Mutex?

I use the .Net Mutex class to lock parts of my app across threads. I'm having some deadlock issues, and it would be very helpful if I could find out the name of the thread that currently has the lock.

Is there an easy way to do that?

Upvotes: 3

Views: 613

Answers (2)

Brian Gideon
Brian Gideon

Reputation: 48959

You could create your own lock class based on Mutux. Obviously you would want to keep it as binary compatible as possible so that you can easily swap the existing references in code with the new class. The WaitOne and ReleaseMutex methods essentially just call into the real Mutex, but add logging or whatever else might be helpful for debugging.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942010

You can't, Mutex is a wrapper around a native Windows handle. Windows obfuscate handle values to prevent anybody from peeking at the internal kernel structures.

Add instrumentation to your code. Easy enough to store the value of the thread's ManagedId or Name every time you acquire the mutex. Logging is often useful to troubleshoot threading problems, although it is dangerous since it affects timing of the threads so much. The VS2010 Ultimate edition has a slick addon named Concurrency Visualizer.

Upvotes: 5

Related Questions