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

前端 未结 7 1830
自闭症患者
自闭症患者 2021-02-09 05:43

I sometimes encounter code in the following form:

while (true) {
  //do something
  Thread.Sleep(1000);
}

I was wondering if this is considered

7条回答
  •  时光取名叫无心
    2021-02-09 05:44

    An alternative approach may be using an AutoResetEvent and instantiate it signaled by default.

    public class Program
    {
         public static readonly AutoResetEvent ResetEvent = new AutoResetEvent(true);
    
         public static void Main(string[] args) 
         {
              Task.Factory.StartNew
              (
                   () => 
                   {
                       // Imagine sleep is a long task which ends in 10 seconds
                       Thread.Sleep(10000);
    
                       // We release the whole AutoResetEvent
                       ResetEvent.Set();
                   }
              );
    
              // Once other thread sets the AutoResetEvent, the program ends
              ResetEvent.WaitOne();
         }
    }
    

    Is the so-called while(true) a bad practice?

    Well, in fact, a literal true as while loop condition may be considered a bad practice, since it's an unbrekeable loop: I would always use a variable condition which may result in true or false.

    When I would use a while loop or something like the AutoResetEvent approach?

    When to use while loop...

    ...when you need to execute code while waiting the program to end.

    When to use AutoResetEvent approach...

    ...when you just need to hold the main thread in order to prevent the program to end, but such main thread just needs to wait until some other thread requests a program exit.

提交回复
热议问题