【发布时间】:2020-07-20 12:03:43
【问题描述】:
我已经阅读了大部分关于 .NET Core 3.1 中的 IHostApplicationLifetime 和 CancellationToken 的文章,但我找不到这不起作用的原因。
我有一个简单的BackgroundService,如下所示:
public class AnotherWorker : BackgroundService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
public AnotherWorker(IHostApplicationLifetime hostApplicationLifetime)
{
_hostApplicationLifetime = hostApplicationLifetime;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine($"Process id: {Process.GetCurrentProcess().Id}");
_hostApplicationLifetime.ApplicationStarted.Register(() => Console.WriteLine("Started"));
_hostApplicationLifetime.ApplicationStopping.Register(() => Console.WriteLine("Stopping"));
_hostApplicationLifetime.ApplicationStopped.Register(() => Console.WriteLine("Stopped"));
return Task.CompletedTask;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("Executing");
return Task.CompletedTask;
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
// This actually prints "Stop. IsCancellationRequested: False". Why?
Console.WriteLine($"Stop. IsCancellationRequested: {cancellationToken.IsCancellationRequested}");
await base.StopAsync(cancellationToken);
}
}
默认添加ConsoleLifetime,监听Ctrl+C和SIGTERM,通知IHostApplicationLifetime。我猜 IHostApplicationLifetime 应该反过来取消所有的 CancellationTokens 吗? Here's a good article on the subject。那么为什么上面代码sn -p的输出如下?
Hosting starting
Started
Hosting started
(sends SIGTERM with `kill -s TERM <process_id>`)
Applicationis shuting down...
Stop. IsCancellationRequested: False
Stopped
Hosting stopped
我希望它记录Stop. IsCancellationRequested: True
我希望能够将此令牌传递给其他服务调用,以便它们能够正常关闭。
【问题讨论】:
-
我不认为它与来自同一个令牌的
IsCancellationRequested相同。要优雅地关闭,您需要在ExecuteAsync上执行此操作。当您在那里执行长时间运行的任务并检查IsCancellationRequested时,它会是真的。CloseAsync只是为了清理那里的一些数据,而不是为了优雅地关闭。传入ExecuteAsync的令牌与CloseAsync不同。
标签: c# .net-core cancellation-token application-lifecycle