As part of trying to gracefully shut down the web host builds a cancellation token in combination with the configured ShutdownTimeout
var timeoutToken = new CancellationTokenSource(Options.ShutdownTimeout).Token;
if (!cancellationToken.CanBeCanceled)
{
cancellationToken = timeoutToken;
}
else
{
cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken).Token;
}
Source
This becomes the shut down token when stopping hosted services
// Fire the IHostedService.Stop
if (_hostedServiceExecutor != null)
{
await _hostedServiceExecutor.StopAsync(cancellationToken).ConfigureAwait(false);
}
In researching the potential issues with hosted services I came across the following from official documentation.
Deployment considerations and takeaways
It is important to note that the way you deploy your ASP.NET Core WebHost or .NET Core Host might impact the final solution. For instance, if you deploy your WebHost on IIS or a regular Azure App Service, your host can be shut down because of app pool recycles. But if you are deploying your host as a container into an orchestrator like Kubernetes or Service Fabric, you can control the assured number of live instances of your host. In addition, you could consider other approaches in the cloud especially made for these scenarios, like Azure Functions.
But even for a WebHost deployed into an app pool, there are scenarios like repopulating or flushing application’s in-memory cache, that would be still applicable.
The IHostedService interface provides a convenient way to start background tasks in an ASP.NET Core web application (in .NET Core 2.0) or in any process/host (starting in .NET Core 2.1 with IHost). Its main benefit is the opportunity you get with the graceful cancellation to clean-up code of your background tasks when the host itself is shutting down.
Now from this based on your concerns I would gather that there is no guarantee that your long running tasks will complete, but they may be given the opportunity for a graceful cancellation based on the hosting environment as explained in the quoted statement above.
Options.ShutdownTimeout
What the default of that value is I am not certain, but it is somewhere to start looking. – Ossa