"while(true){Thread.Sleep}"的原因是什么? [英] What is the reason for "while(true) { Thread.Sleep }"?
问题描述
我有时会遇到以下形式的代码:
I sometimes encounter code in the following form:
while (true) {
//do something
Thread.Sleep(1000);
}
我想知道这是好事还是坏事,是否还有其他选择.
I was wondering if this is considered good or bad practice and if there are any alternatives.
通常,我在服务的主要功能中找到"这样的代码.
Usually I "find" such code in the main-function of services.
我最近在Windows azure worker角色的运行"功能中看到了具有以下格式的代码:
I recently saw code in the "Run" function in a windows azure worker role which had the following form:
ClassXYZ xyz = new ClassXYZ(); //ClassXYZ creates separate Threads which execute code
while (true) {
Thread.Sleep(1000);
}
我认为有更好的方法可以防止服务(或天蓝色工作人员角色)退出. 有人对我有建议吗?
I assume there are better ways to prevent a service (or azure worker role) from exiting. Does anyone have a suggestion for me?
推荐答案
使用Thread.Sleep(1000)
执行此操作时,处理器将浪费很少的时间来唤醒并且不执行任何操作.
Well when you do that with Thread.Sleep(1000)
, your processor wastes a tiny amount of time to wake up and do nothing.
您可以使用 CancelationTokenSource 做类似的事情.
You could do something similar with CancelationTokenSource.
当您呼叫WaitOne()
时,它将等待直到收到信号为止.
When you call WaitOne()
, it will wait until it receives a signal.
CancellationTokenSource cancelSource = new CancellationTokenSource();
public override void Run()
{
//do stuff
cancelSource.Token.WaitHandle.WaitOne();
}
public override void OnStop()
{
cancelSource.Cancel();
}
这将使Run()方法退出,而不会在忙于等待时浪费您的CPU时间.
This will keep the Run() method from exiting without wasting your CPU time on busy waiting.
这篇关于"while(true){Thread.Sleep}"的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!