What is the reason for "while(true) { Thread.Sleep }"?

Preli picture Preli · May 12, 2014 · Viewed 13.6k times · Source

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.

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?

Answer

Dávid Kaya picture Dávid Kaya · May 12, 2014

Well when you do that with Thread.Sleep(1000), your processor wastes a tiny amount of time to wake up and do nothing.

You could do something similar with CancelationTokenSource.

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();
}

This will keep the Run() method from exiting without wasting your CPU time on busy waiting.