简体   繁体   中英

Await inside System.Threading.Timer callback

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?

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 .

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