views:

487

answers:

3

Periodically we get a hang on shut down of a Windows service in a production environment that we just cannot reproduce. It can be months before it happens again.

I'm putting in some diagnostics to try and help with the issue, one thing I'm looking at is adding an event to the system thread pool for 60 seconds after we initiate shut down of the application. Our application should shutdown cleanly within 10 seconds maximium.

In this event I would like to trace out the remaining running threads of the process to the event log.

I can get the running threads using System.Diagnostics.Process.GetCurrentProcess.Threads. These threads objects have native Win32 thread id's etc.

I was wondering if there was any way of getting back from these thread id's to any managed threads that they represent in the current process. The reason I am trying to do this is because for our thread pools and other threads we spawn we give the names which represent their purpose and it would really help to get these back.

Kind Regards

Noel

+3  A: 

This is impossible for the following reason. Quote from MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

So there's no one-to-one mapping between managed threads and OS threads.

So now the question becomes, how to get a list of all the managed threads currently running in the current process? Unfortunately I don't know the answer.

Darin Dimitrov
Thanks Darin. I had kind of reached that conclusion myself from reading on the web. Was hoping someone out there might have known a bit of magic to throw at this issue that might have done the trick. I am currently tracing out all the unmanaged thread information I can get my hands on. Will look at putting in similar information for all managed threads at creation time where I have access to that functionality. Hopefully I'll get some correlation between them.
Bigtoe
A: 

It does not look like this is possible. Luckily for us we have our own threading libraries which wrap the .NET libraries and I was able to put in functionality to keep a list of active threads that we can use for these diagnostics. This works quite well but there was a fair bit of effort involved and testing of course, but hopefully we'll get o the bottom of it.

Thanks

Kind Regards

Noel

Bigtoe
A: 

This topic discusses the same problem but suggested solution does not seem to work for me (throws InvalidCastException when casting from ProcessThread to Thread): http://stackoverflow.com/questions/2057781/is-there-a-way-to-get-the-stacktraces-for-all-threads-in-c-like-java-lang-threa

Hans Løken