ThreadState
One can query a thread's execution status via its ThreadState property. Figure 1 shows one "layer" of the ThreadState enumeration.
ThreadState is horribly designed, in that it combines three "layers" of state using bitwise flags, the members within each layer being themselves mutually exclusive.
Here are all three layers:
- The Running / Blocking / Aborting status (as shown in Figure 1)
- The Background/Foreground status (ThreadState.Background)
- The progress towards suspension via the deprecated Suspend method(ThreadState.SuspendRequested and ThreadState.Suspended)
In total then, ThreadState is a bitwise combination of zero or one members from each layer!.Here are some sample ThreadStates:
- Unstarted
- Running
- WaitSleepJoin
- Background, Unstarted
- SuspendRequested, Background, WaitSleepJoin
Note - The enumeration has two members that are never used, at least in the current CLR implementation: StopRequested and Aborted.
| class Terminator { static void { Thread t = new Thread(Work); Console.WriteLine(t.ThreadState); // Unstarted t.Start(); Thread.Sleep(1000); Console.WriteLine(t.ThreadState); // Running t.Abort(); Console.WriteLine(t.ThreadState); // AbortRequested t.Join(); Console.WriteLine(t.ThreadState); // Stopped } static void Work() { while (true) { try { while (true); } catch (ThreadAbortException) {} } } } |
| |
ThreadState is invaluable for debugging or profiling. It's poorly suited, however, to coordinating multiple threads, because no mechanism exists by which one can test a ThreadState and then act upon that information, without the ThreadState potentially changing in the interim.
Hope this helps.
Thanks & Regards,
Arun Manglick || Senior Tech Lead
No comments:
Post a Comment