views:

180

answers:

3

This question got me thinking about the .NET equivalent. What value is there to the ThreadState property of the Thread class? In this code example:

        if (someThread.ThreadState != System.Threading.ThreadState.Running)
        {
            someThread = new Thread(SomeMethod);
            someThread.Start();
        }

The someThread's ThreadState property could switch to Running between the if and the code inside the if, right?

+1  A: 

From MSDN:

Important Note:
There are two thread state enumerations, System.Threading.ThreadState and System.Diagnostics.ThreadState. The thread state enumerations are only of interest in a few debugging scenarios. Your code should never use thread state to synchronize the activities of threads.

Kevin Montrose
So why would I be interested in it and what would I do to solve the synchronization problem?
jasonh
Unless you're debugging, ignore ThreadState; its not a solution to anything.
Kevin Montrose
+1  A: 

ThreadState is useful for looking at in the debugger, in order to help understand and debug certain types of blocking/synchronization bugs. For example, you can tell if a specific thread is blocked in the debugger by looking at this, and seeing the ThreadState set to ThreadState.WaitSleepJoin.

That being said, it's something I almost never rely upon. I've had mixed results trying to debug using this, so in general, I think it's really most often best to pretend that it doesn't exist.

Reed Copsey
+2  A: 

ThreadState is one of those fantastic properties that look promising at first, but once you dive deep into the way in which in functions, you find that it's almost totally useless.

The main problem with ThreadState is the enumeration names are very misleading. For instance take ThreadState.Runnning. This is a really bad name because it does not actually indicate the thread is running. Instead it indicates the thread was running at some point in the recent past and may or may not still be running.

This may seem trivial but it's not. It's really easy to take the names of the enumeration literally and produces really nice looking code. However as well as the code reads, it's often based on flawed logic.

I really only use this property for debugging purposes.

This value can be useful in very limited sets of scenarios where you have some other mechanism which controls the thread you are looking at. Such as a lock or WaitHandle. But it's usually better to use another form of synchronization than relying on this property.

JaredPar