Search code examples
c#asp.netasync-awaittimerbackground

Await inside System.Threading.Timer callback


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?


Solution

  • 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.