Using Thread.Sleep or Timer in Azure worker role in .NET? Using Thread.Sleep or Timer in Azure worker role in .NET? azure azure

Using Thread.Sleep or Timer in Azure worker role in .NET?


The purpose of the Thread.Sleep() loop is to keep the Run() method from exiting. If Run() exits, then your worker will restart. I don't know that you could accomplish that goal effectively with a Timer.

Most likely your CPU is wasting some tiny amount of time to wake up that thread every 1000 msecs in order to do nothing. I doubt it's significant, but it bugged me too. My solution was to wait on a CancellationToken instead.

public class WorkerRole : RoleEntryPoint {    CancellationTokenSource cancelSource = new CancellationTokenSource();    public override void Run()    {        //do stuff        cancelSource.Token.WaitHandle.WaitOne();    }    public override void OnStop()    {        cancelSource.Cancel();    }}

This keeps the Run() method from exiting without wasting CPU time on busy waiting. You can also use the CancellationToken elsewhere in your program to initiate any other shutdown operations you may need to perform.