0

I am doing an ASP.NET Web API and have a BackgroundService like this:

enter image description here

Inside Doing, I to await a task 1:

enter image description here

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 :

enter image description here

How can I resolve this? Or is there a way to achieve a background task with await for the task completion?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
eragon
  • 13
  • 3
  • 2
    **Please** don't use pictures of code in your questions, copy and paste your code as text, and then format it as `code` – Flydog57 Mar 06 '22 at 18:28

1 Answers1

2

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.

pfx
  • 20,323
  • 43
  • 37
  • 57
  • Or you can use the new (.NET 6) [`PeriodicTimer`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.periodictimer) class, as shown [here](https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval/62724908#62724908), for a consistently periodic ticking of the timer. – Theodor Zoulias Mar 06 '22 at 19:03