Writing an infinite loop is simple:
while(true){
//add whatever break condition here
}
But this will trash the CPU performance. This execution thread will take as much as possible from CPU's power.
What is the best way to lower the impact on CPU?
Adding some Thread.Sleep(n)
should do the trick, but setting a high timeout value for Sleep()
method may indicate an unresponsive application to the operating system.
Let's say I need to perform a task each minute or so in a console app.
I need to keep Main()
running in an "infinite loop" while a timer will fire the event that will do the job. I would like to keep Main()
with the lowest impact on CPU.
What methods do you suggest. Sleep()
can be ok, but as I already mentioned, this might indicate an unresponsive thread to the operating system.
LATER EDIT:
I want to explain better what I am looking for:
I need a console app not Windows service. Console apps can simulate the Windows services on Windows Mobile 6.x systems with Compact Framework.
I need a way to keep the app alive as long as the Windows Mobile device is running.
We all know that the console app runs as long as its static Main() function runs, so I need a way to prevent Main() function exit.
In special situations (like: updating the app), I need to request the app to stop, so I need to infinitely loop and test for some exit condition. For example, this is why
Console.ReadLine()
is no use for me. There is no exit condition check.Regarding the above, I still want Main() function as resource friendly as possible. Let asside the fingerprint of the function that checks for the exit condition.
Thread.Sleep(0)
is probably good – FibTimer
? – NorrySleep(0)
relinquishes the remainder of the current time-slice, but it still leads to 100% CPU utilization. So it doesn't work here. – IzSleep(0)
results in 'whatever % isn't being used elsewhere' which is sometimes pretty cool - especially when making an application that uses 'remaining resources' to do its work (e.g. SETI@Home or something would be a use case). – Rescissory