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

前端 未结 7 1806
自闭症患者
自闭症患者 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 06:01

    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.

提交回复
热议问题