The following code strips a ThreadState to one of the four most useful values: Unstarted, Running,WaitSleepJoin, and Stopped:
public static ThreadState SimpleThreadState (ThreadState ts)
{
return ts & (ThreadState.Unstarted |
ThreadState.WaitSleepJoin |
ThreadState.Stopped);
}
I read the above in a book, but I am not quite sure what the author want to illustrate here. I have tested like below:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(SimpleThreadState(ThreadState.Aborted));
System.Console.WriteLine(SimpleThreadState(ThreadState.Background));
System.Console.WriteLine(SimpleThreadState(ThreadState.AbortRequested));
System.Console.WriteLine(SimpleThreadState(ThreadState.Suspended));
System.Console.WriteLine(SimpleThreadState(ThreadState.Unstarted));
System.Console.WriteLine(SimpleThreadState(ThreadState.WaitSleepJoin));
System.Console.WriteLine(SimpleThreadState(ThreadState.Stopped));
}
public static ThreadState SimpleThreadState(ThreadState ts)
{
return ts & (ThreadState.Unstarted |
ThreadState.WaitSleepJoin |
ThreadState.Stopped);
}
}
And here is the running result:
Running
Running
Running
Running
Unstarted
WaitSleepJoin
Stopped
The last three lines of output is straight forward, but why all else outputs Running state?
Thanks!
Bascially this is a binary mask. By or’ing together
ThreadState.Unstarted, ThreadState.WaitSleepJoin,ThreadState.Stopped you construct a mask. When you
andthat mask with another value tells if you an of the other bits are still turned on.Let’s pretend that we’re dealing with a four bit int Thread.Unstarted == 1, ThreadState.WaitSleepJoing==2, ThreadState.Stopped==4, ThreadState.Aborted= 8 and ThreadState.Running = 0 . These are not the real values, just using them to make the example easier. Look at ThreadState for the real values.
So in binary:
Thread.Unstarted == 0001
Thread.WaitSleepJoing == 0010
Thread.Stopped == 0100
When you
orthese values together you get 0111.Now when we
and0111 with ThreadState.Aborted (1000) you get 0000 which is ThreadState.Running.So what the author is basically trying to show you here is that ThreadState is a bit vector and you have to construct a mask to see which values are set.