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

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

    I personally don't like Thread.Sleep code. Because it locks the main thread. You can write something like this, if it is a windows application besides it allows you more flexibility and you can call it async:

    bool switchControl = true;
    
    while (switchControl) {
      //do something
      await Wait(1);
    }
    
    async void Wait(int Seconds)
    {
      DateTime Tthen = DateTime.Now;
      do
      {
        Application.DoEvents(); //Or something else or leave empty;
      } while (Tthen.AddSeconds(Seconds) > DateTime.Now);
    }
    

提交回复
热议问题