![](/img/trans.png)
[英].Net core IHostedService Background task exception will not terminate application
[英]How can I manually cancel a .NET core IHostedService background task?
我想在 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);
}
}
}
我不太明白ExecuteAsync
只被框架調用一次的事實。 因此,答案很簡單,完成后跳出循環。
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;
}
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.