我想知道调用 Thread.Sleep(1) 和调用 SwitchToThread 之间的实际区别是什么(如果我们忽略它目前未被 BCL 公开)。
Joe Duffy 在 his post 中提到那:
"The kernel32!SwitchToThread API doesn't exhibit the problems that Sleep(0) and Sleep(1) do." (regarding the scheduler's behavior)
为什么 Sleep 的行为与 SwitchToThread 不同?为什么存在这种差异,它有什么好处? (如果有的话……)
最佳答案
有两个区别。第一个在 MSDN 文档中提到了 SwitchToThread :
The yield of execution is limited to the processor of the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority.
Sleep(0) 也将允许其他处理器上的线程运行。
SwitchToThread 也只屈服于单线程调度上下文。另一方面, sleep 有多种等待条件。 SleepEx 的文档详细说明:
* An I/O completion callback function is called
* An asynchronous procedure call (APC) is queued to the thread.
* The time-out interval elapses
这将屈服于多个线程。
一般来说,Sleep(0) 更有可能产生一个时间片,并且总是会产生给操作系统,即使没有其他线程在等待。这就是为什么在许多情况下,在循环中添加 Sleep(0) 会使处理器使用率从 100%(每个内核)降低到接近 0%。 SwitchToThread 不会,除非另一个线程正在等待时间片。
关于c# - SwitchToThread 与 sleep (1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1383943/