简体   繁体   中英

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));
    }
}

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/as.net/core/fundamentals/host/hosted-services?view=as.netcore-3.1&tabs=visual-studio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM