Sunday, August 31, 2008

Probing thread state in .NET application

In multi-threaded application, some threads could be running fine, others might have problem. While trouble-shooting bug in a multi-threaded application, someone pointed me out that there are 2 set of thread id and thread state can be probed:
1) ThreadState Enumeration in System.Diagnostics (in system.dll)
2) ThreadState Enumeration in System.Threading (in mscorlib.dll)

While the enumerate members can be found in MSDN easily, the associate integer value is a bit tricky. And using Reflector, its values are:


and


While it's easy to use "Thread.CurrentThread" to check the state of the current thread, most of the time we need to monitor all the threads. Furthermore you will get a whole different set of thread id, if using property "Thread.CurrentThread.ManagedThreadId". Thus, classes like "ProcessThreadCollection":

For Each threCurr As ProcessThread In Process.GetCurrentProcess().Threads
Console.WriteLine("ID : " + CStr(threCurr.Id) + " ; State : " + CStr(threCurr.ThreadState))
Next

will be useful to enumerate all the threads in your application, especially you can simply use any other third party tool like Process-Explorer to probe all the thread easily, in real-time:

No comments: