(Post 19/10/2007) 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. Figure 1: Thread State Diagram | |
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 (The enumeration has two members that are never used, at least in the current CLR implementation: StopRequested and Aborted) To complicate matters further, ThreadState.Running has an underlying value of 0, so the following test does not work: if ((t.ThreadState & ThreadState.Running) > 0) ... and one must instead test for a running thread by exclusion, or alternatively, use the thread's IsAlive property. IsAlive, however, might not be what you want. It returns true if the thread's blocked or suspended (the only time it returns false is before the thread has started, and after it has ended). Assuming one steers clear of the deprecated Suspend and Resume methods, one can write a helper method that eliminates all but members of the first layer, allowing simple equality tests to be performed. A thread's background status can be obtained independently via its IsBackground property, so only the first layer actually has useful information: public static ThreadState SimpleThreadState (ThreadState ts) { return ts & (ThreadState.Aborted | ThreadState.AbortRequested | ThreadState.Stopped | ThreadState.Unstarted | ThreadState.WaitSleepJoin); } 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. (Sưu tầm) |