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

前端 未结 7 1810
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 06:05

    If you use while(true) you have no programmatic means of ending the loop from outside the loop.

    I'd prefer, at least, a while(mySingletonValue) which would allow us to switch the loop as needed.

    An additional approach would be to remove the functional behavior from the looping behavior. Your loop my still be infinite but it calls a function defined elsewhere. Therefore the looping behavior is completely isolated to what is being executed by the loop:

    while(GetMySingletonValue())
    {
        someFunction();
    }
    

    In this way your singleton controls the looping behavior entirely.

提交回复
热议问题