CPU friendly infinite loop

前端 未结 11 1907
心在旅途
心在旅途 2020-12-04 09:15

Writing an infinite loop is simple:

while(true){
    //add whatever break condition here
}

But this will trash the CPU performance. This ex

11条回答
  •  一整个雨季
    2020-12-04 09:54

    Lots of "advanced" answers here but IMO simply using a Thread.Sleep(lowvalue) should suffice for most.

    Timers are also a solution, but the code behind a timer is also an infinity loop - I would assume - that fires your code on elapsed intervals, but they have the correct infinity-loop setup.

    If you need a large sleep, you can cut it into smaller sleeps.

    So something like this is a simple and easy 0% CPU solution for a non-UI app.

    static void Main(string[] args)
    {
        bool wait = true;
        int sleepLen = 1 * 60 * 1000; // 1 minute
        while (wait)
        {
    
            //... your code
    
            var sleepCount = sleepLen / 100;
            for (int i = 0; i < sleepCount; i++)
            {
                Thread.Sleep(100);
            }
        }
    }
    

    Regarding how the OS detects if the app is unresponsive. I do not know of any other tests than on UI applications, where there are methods to check if the UI thread processes UI code. Thread sleeps on the UI will easily be discovered. The Windows "Application is unresponsive" uses a simple native method "SendMessageTimeout" to see detect if the app has an unresponse UI.

    Any infinity loop on an UI app should always be run in a separate thread.

提交回复
热议问题