I have a situation where I need a constant loop running in a service, each time checking certain conditions, and then taking action as appropriate. From a design perspective, using a while (true) loop fits perfectly:
while (true)
{
Process();
}
The Process() method checks the state of an in-memory (fast) data store. If it finds there is work to do based on the state, it Processes it using Task.Run() (so control returns to the loop immediately).
I have seen some references that this will eat up unnecessary CPU cycles, and that I should use a Timer, or add Thread.Sleep to the loop. I have also seen posts stating that there is nothing wrong with using while (true).
On my dev machine, it does not seem to have a negative impact, although the CPU usage does go up. It may be that the CPU usage gets spread across multiple cores, where the deployment environment may only have a single core.
Does a while (true) loop have a negative performance impact on the CPU, and if so, what is the correct way to mitigate the impact?
The answer is of course it depends on what you are doing.
A while(true) loop doesn't intrinsically cause bad performance on it's own. The performance danger occurs in the method body, in this case Process().
If the method is intended to run forever and never take a break than this construct is fine. However, if Process is supposed to respond to events or 'listen' for something to occur, placing it in a while(true) loop can cause your processor to unnecessarily poll.
For example,
while (true)
{
//At the start of every minute
if (DateTime.Now.Seconds == 0)
//Do Something
}
This would be very bad. You're having your CPU constantly check a condition that's only true once a minute and preventing the CPU from doing useful work the remainder of the time.
In a situation like this, you'd be better of using some of the functionality available to you in the Threading namespace to release the CPU.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With