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?