c# - 在 C# .NET 标准中,为什么使用位测试 "Running"确定线程状态 `(ThreadState & (Stopped | Unstarted)) == 0`

标签 c# multithreading

根据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/

相关文章:

c# - 如何从 BitmapImage 获取 BitmapSource?

c# - 选择通过与其分组的另一个属性值找到的 XML 属性值。

java - 使用 JPA 提高 foreach 持久调用的性能

java - 如果没有输入任何内容,如何检查 Scanner.hasNext(System.in) 是否超时?

python - python 中的奇怪线程行为

java - 有多少个可调用对象?

c# - 来自线程的异常不会冒泡到主线程

c# - 扩展 System.Object 时如何避免装箱/拆箱?

c# - 线程敏捷性是否出现在 ASP.Net MVC 中?

java - 在 Java 性能方面处理 API 的最佳方法。 (单独的线程与单个更新线程)