How to tell if a thread has exited successfully?

Mark Carpenter picture Mark Carpenter · Jun 16, 2009 · Viewed 8.4k times · Source

According to the MSDN Documentation for ThreadState, the Stopped state can be entered by one of two ways: the thread exiting, or the thread being aborted.

Is there some mechanism for telling whether a thread has entered the Stopped state by exiting normally? Thanks!

Answer

LBushkin picture LBushkin · Jun 16, 2009

A thread can reach the Stopped state in several ways:

  • It's main method can exit without any errors.
  • An uncaught exception on the thread can terminate it.
  • Another thread could call Thread.Abort(), which will cause a ThreadAbortException to be thrown on that thread.

I don't know if you are looking to differentiate between all three states, but if all you are really interested in is whether the thread completed successfully, I would suggest using a shared data structure of some kind (a synchronized dictionary would work) that the main loop of a thread updates as it terminates. You can use the ThreadName property as the key in this shared dictionary. Other threads that are interested in termination state, could read from this dictionary to determine the final status of the thread.

After looking a bit more at the MSDN documentation, you should be able to differentiate an externally aborted thread using the ThreadState property. This should be set to ThreadState.Aborted when a thread responds to the Abort() call. However, unless you have control of the thread code that is run, I don't think that you can differentiate between a thread that just exited its main method, vs one that terminated with an exception.

Keep in mind however, if you control the code that starts the thread, you can always substitute your own method that internally calls the code that runs the main thread logic and inject exception detection (as I described above) there.