简体   繁体   English

在 System.Threading.Timer 回调中等待

[英]Await inside System.Threading.Timer callback

I am doing an ASP.NET Web API and have a BackgroundService like this:我正在做一个 ASP.NET Web API 并且有这样的BackgroundService

在此处输入图像描述

Inside Doing , I to await a task 1:Doing中,我等待任务 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.问题在于TimeSpan.FromSeconds(0.5)) ExecuteAsync会创建一个新的Doing()而无需等待我的任务完成。

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 .不要使用Timer Instead set up a loop and use Task.Delay for the wait period.而是设置一个loop并在等待期间使用Task.Delay

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 .请参阅Microsoft 文档中的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM