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));
}
}
CodePudding user response:
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
}
}
}