根据documentation , :
Because the Running state has a value of 0, it is not possible to perform a bit test to discover this state. Instead, the following test (in pseudo-code) can be used:
if ((state & (Unstarted | Stopped)) == 0) // implies Running
Threads are often in more than one state at any given time.
和api
The Thread.ThreadState property of a thread provides the current state of a thread. Applications must use a bitmask to determine whether a thread is running. Since the value for
Running
is zero (0), test whether a thread is running by using C# code such as(myThread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0
or Visual Basic code such as(myThread.ThreadState And (ThreadState.Stopped Or ThreadState.Unstarted)) = 0
.
搜索 SO ( 1 , 2 , 3 ) 我只发现为什么 ThreadState 不应该用于流量控制,因为检查的状态可以立即改变。对于检查它以进行调试的情况,为什么要使用上面的位掩码而不是仅使用 myThread.ThreadState==0
?
最佳答案
此处的枚举/位掩码限制您检查两位。状态中有其他位不会告诉您它是否正在运行 - 因此它们被设置为 (1) 或未被设置 (0) 不会改变你是否应该考虑它运行。例如,设置 WaitSleepJoin
位或设置 SuspendRequested
位 - 对于最有用的目的,不会改变它正在“运行”。
因此:state & (Unstarted | Stopped)
表示“只查看这两位,忽略其余部分”...
完整的记录标志是:
[Serializable, Flags, ComVisible(true)]
public enum ThreadState
{
Aborted = 256,
AbortRequested = 128,
Background = 4,
Running = 0,
Stopped = 16,
StopRequested = 1,
Suspended = 64,
SuspendRequested = 2,
Unstarted = 8,
WaitSleepJoin = 32
}
我说“已记录”,因为没有强制执行枚举 - 理论上该值可以返回为 2050 或 -6 - 为这些设置任何位标志。
关于c# - 在 C# .NET 标准中,为什么使用位测试 "Running"确定线程状态 `(ThreadState & (Stopped | Unstarted)) == 0`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48595261/