Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c# - What value is the ThreadState Property?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...