我知道在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工作者中使用是好还是坏?
任何解释与某些资源的链接的解释都是受欢迎的,因为到目前为止我找不到任何东西.
我有时会遇到以下形式的代码:
while (true) {
//do something
Thread.Sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
我想知道这是否被认为是好的或坏的做法,如果有任何替代方案.
通常我会在服务的主要功能中"找到"这样的代码.
我最近在windows azure worker角色的"运行"功能中看到了具有以下形式的代码:
ClassXYZ xyz = new ClassXYZ(); //ClassXYZ creates separate Threads which execute code
while (true) {
Thread.Sleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
我假设有更好的方法来阻止服务(或天蓝色工作者角色)退出.有人对我有建议吗?