CPU friendly infinite loop

前端 未结 11 1922
心在旅途
心在旅途 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:45

    Why don't you write a small application and use the system's task scheduler to run it every minute, hour...etc?

    Another option would be to write a Windows Service which runs in the background. The service could use a simple Alarm class like the following on MSDN:

    http://msdn.microsoft.com/en-us/library/wkzf914z%28v=VS.90%29.aspx#Y2400

    You can use it to periodically trigger your method. Internally this Alarm class uses a timer:

    http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

    Just set the timer's interval correctly (e.g. 60000 milliseconds) and it will raise the Elapsed event periodically. Attach an event handler to the Elapsed event to perform your task. No need to implement an "infinite loop" just to keep the application alive. This is handled for you by the service.

提交回复
热议问题