C# Thread.Sleep 或 Thread.Yield
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11480912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thread.Sleep or Thread.Yield
提问by poco
I have a method that uses a background worker to poll a DLL for a status looking something like this:
我有一种方法,它使用后台工作者轮询 DLL 以获取如下所示的状态:
var timeout = DateTime.Now.AddSeconds(3);
while (System.Status != Status.Complete // our status is not complete
&& DateTime.Now < timeout // have not timed out
&& !_Worker.CancellationPending) // backgroundworker has not been canceled
{
//Thread.Yield();
//Thread.SpinWait(1);
//Thread.Sleep(1);
}
When looking at my CPU %, yield()and spinwait()cause my app to shoot up to 50% on my PC. With Sleep(1)my CPU % stays down at 6%. I have been told that that I should choose Thread.Yield(), however the spikes in CPU % bother me. What is best practice for something like this?
在查看我的 CPU % 时,yield()并spinwait()导致我的应用程序在我的 PC 上高达 50%。随着Sleep(1)我的CPU%,6%,保持了下来。有人告诉我应该选择Thread.Yield(),但是 CPU % 的峰值困扰着我。这样的事情的最佳实践是什么?
采纳答案by Eric J.
Thread.Yieldwill interrupt the current thread to allow other threads to do work. However, if they do not have any work to do, your thread will soon be rescheduled and will continue to poll, thus 100% utilization of 1 core.
Thread.Yield将中断当前线程以允许其他线程工作。但是,如果他们没有任何工作要做,您的线程将很快被重新安排并继续轮询,因此 1 个核心的利用率为 100%。
Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.
使调用线程将执行权交给另一个准备好在当前处理器上运行的线程。操作系统选择要屈服的线程。
Thread.Sleepwill schedule your thread to run again after the sleep time expires, thus much lower CPU utilization.
Thread.Sleep将安排您的线程在睡眠时间到期后再次运行,从而大大降低 CPU 利用率。
Blocks the current thread for the specified number of milliseconds.
在指定的毫秒数内阻塞当前线程。
Given the choice between the two, Thread.Sleepis better suited for your task. However, I agree with the comment from @Bryan that a Threading.Timermakes for a more elegant solution.
鉴于两者之间的选择,Thread.Sleep更适合您的任务。但是,我同意 @Bryan 的评论,即 aThreading.Timer可以提供更优雅的解决方案。

