c# - SwitchToThread 与 sleep (1)

标签 c# .net multithreading winapi sleep

我想知道调用 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/

相关文章:

multithreading - 并行编码与多线程(在单个CPU上)

Python - ThreadPoolExecutor 阻塞。如何解锁

c# - MVC 应用程序 - 这是使用 Async 和 Await 的正确方法吗?

c# - .net 4 应用程序运行 .net 2.0 程序集

c# - 保存位图导致通用 GDI+ 错误

c# - WPF 自定义 LED 复选框

c# - 使用 LINQ 查找缺少父对象的子对象

Linux RT Preempt - 是否需要 POSIX 线程?

c# - 如何使用 NewtonSoft Json 序列化 FileInfo 对象?

c# - 我们可以在 BackgroundWorker 中使用 DispatcherTimer 吗?