I am doing an ASP.NET Web API and have a BackgroundService like this:
Inside Doing, I to await a task 1:
The problem is with the TimeSpan.FromSeconds(0.5)) the ExecuteAsync will do create a new Doing() without waiting for my task to be done.
The console result :
How can I resolve this? Or is there a way to achieve a background task with await for the task completion?
CodePudding user response:
Don't use a Timer.
Instead set up a loop and use Task.Delay for the wait period.
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
var delay = TimeSpan.FromSeconds(0.5);
while (!cancellationToken.IsCancellationRequested)
{
await Doing();
await Task.Delay(delay, cancellationToken);
}
}
See an example in Microsofts documentation.



