应如何在 IHostedService 中使用取消令牌?

How should cancellation tokens be used in IHostedService?

ASP.NET Core 2.0 documentation定义IHostedService接口如下:

StartAsync(CancellationToken) - Called after the server has started and IApplicationLifetime.ApplicationStarted is triggered. StartAsync contains the logic to start the background task.

StopAsync(CancellationToken) - Triggered when the host is performing a graceful shutdown. StopAsync contains the logic to end the background task and dispose of any unmanaged resources. If the app shuts down unexpectedly (for example, the app's process fails), StopAsync might not be called.

如果调用StopAsync关闭服务,那么取消令牌参数有什么用?它们究竟应该如何使用?

传递给 IHostedService.StopAsync() 的取消标记来自 WebHost.StopAsync() and is usually a cancellation token that is tied to the default shutdown command for an ASP.NET Core application (e.g. CTRL + C or SIGTERM). This token is linked with a new token that is tied to a (configurable) time-out. For example, see the RunAsync() extension method。我相信默认超时是 5 秒。这意味着当主持人在令牌源上调用 Cancel() 或超时开始时,将请求取消。