在.NET中的Azure辅助角色中使用Thread.Sleep或Timer?

Gui*_*ume 9 .net multithreading timer azure azure-worker-roles

我知道在Windows服务中,最好使用Timer而不是Thread.Sleep(timeout).但是,在我可以在因特网上找到的处理Azure工作者的所有代码示例中,Thread.Sleep(timeout)使用的是代替它的Timer.

甚至Visual Studio中的Worker项目模板中提供的默认代码也使用Thread.Sleep:

public class WorkerRole : RoleEntryPoint
{
    public override void Run()
    {
        // This is a sample worker implementation. Replace with your logic.
        Trace.WriteLine("$projectname$ entry point called", "Information");

        while (true)
        {
            Thread.Sleep(10000);
            Trace.WriteLine("Working", "Information");
        }
    }
// ...
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在使用Thread.Sleep我的工作人员,但没有真正理解为什么.所以我的问题是,为什么Thread.Sleep(timeout)在Azure工作者角色中使用而不是Timer?Windows服务和Azure工作人员之间的区别是什么导致我们应该如何构思这种应用程序?Timer在Azure工作者中使用是好还是坏?

任何解释与某些资源的链接的解释都是受欢迎的,因为到目前为止我找不到任何东西.

Bri*_*chl 15

Thread.Sleep()循环的目的是防止Run()方法退出.如果Run()退出,那么您的工作人员将重新启动.我不知道你可以用Timer有效地实现这个目标.

很可能你的CPU浪费了一点点时间来唤醒每1000毫秒的线程,以便什么都不做.我怀疑这很重要,但它也让我感到烦恼.我的解决方案是等待CancellationToken.

public class WorkerRole : RoleEntryPoint {
    CancellationTokenSource cancelSource = new CancellationTokenSource();

    public override void Run()
    {
        //do stuff
        cancelSource.Token.WaitHandle.WaitOne();
    }

    public override void OnStop()
    {
        cancelSource.Cancel();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样可以防止Run()方法退出,而不会在繁忙等待时浪费CPU时间.您还可以使用程序中其他位置的CancellationToken来启动您可能需要执行的任何其他关闭操作.

  • `Thread.Sleep(Timeout.Infinity)`解决方案是如何阻止等待`WaitHandle`的呢?就此而言,为什么不使用`ManualResetEvent`?这很可能是同样的事情. (2认同)