我希望在Startup.cs完成后进行一些异步工作。 我通过扩展BackgroundService
实现了一些异步任务的后台服务。
我的问题是如何在我决定的时间取消运行任务? 我只能看到文档中延迟下一个周期的示例。
我尝试手动执行StopAsync
,但while循环会无限执行(令牌未被取消,虽然我觉得应该被取消,因为我已经将令牌传递给了StopAsync
,而且实现看起来就像它应该这样做)。
这是一些简化的代码:
public class MyBackgroundService : BackgroundService
{
private readonly ILogger<MyBackgroundService> _logger;
public MyBackgroundService(ILogger<MyBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("MyBackgroundService is starting.");
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("MyBackgroundService task doing background work.");
var success = await DoOperation();
if (!success)
{
// Try again in 5 seconds
await Task.Delay(5000, stoppingToken);
continue;
}
await StopAsync(stoppingToken);
}
}
}