Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should cancellation tokens be used in IHostedService?

The ASP.NET Core 2.0 documentation defines the IHostedService interface as follows:

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.

If StopAsync is called to shut down the service, then what are the cancellation token parameters used for? How exactly should they be used?

like image 461
emagdne Avatar asked Apr 30 '18 15:04

emagdne


1 Answers

The cancellation token passed to IHostedService.StopAsync() originates from 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. I believe the default time-out is 5 seconds. This means that cancellation will be requested when the host calls Cancel() on the token source or when the time-out kicks in.

like image 105
Henk Mollema Avatar answered Sep 20 '22 13:09

Henk Mollema