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:
- 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.
| || |
Thread t = new Thread(Work);
Console.WriteLine(t.ThreadState); // Unstarted
Console.WriteLine(t.ThreadState); // Running
Console.WriteLine(t.ThreadState); // AbortRequested
Console.WriteLine(t.ThreadState); // Stopped
static void Work()
| || |
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