Search code examples
c#.netbackground-service.net-4.8

While true or while true with Thread.Sleep in a background service


I'm creating a background service that needs to run each x seconds. It has to be in .net Framework as the client does not want to upgrade to core or install anything on the machine other than this app. So I am restricted to using the Windows Service

My main issue is that I'm going in a while(true) loop that checks for the passed time (yes, I know I could use a timer) and I'm not sure if I should add a thread. Sleep in the loop or just leave the while(true). My main concern is not to overload the CPU/memory.

var nextIteration = DateTime.Now.Add(TimeSpan.FromSeconds(timer * (-1)));

while (true)
{
    if (nextIteration < DateTime.Now)
    {
        RunService();
        nextIteration = DateTime.Now.Add(TimeSpan.FromSeconds(timer));
    }
}

Solution

  • If you are implementing a service of type BackgroundService you should consider using the CancellationToken in your while:

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {    
            try
            {
                 //do work
                 await Task.Delay(TimeSpan.FromSeconds(x), stoppingToken);
            }
            catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
            {
                //handle cancelation requested exception
            }
            catch (Exception ex)
            {
                //handle ex
            }          
        }
    }
    

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio