Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...