Advertisement
Advanced ASP.NET Core, Background Tasks & Hosted Services

How does graceful shutdown work for a BackgroundService, and how should ExecuteAsync respect the CancellationToken?

Short answer

When the host begins shutting down, it signals the CancellationToken passed to ExecuteAsync and gives the service a configurable grace period (ShutdownTimeout, default 30 seconds) to finish current work and exit cleanly before being forcibly terminated -- well-behaved…

Save ASP.NET Core mock interview
Advertisement
AModel answer
When the host begins shutting down, it signals the CancellationToken passed to ExecuteAsync and gives the service a configurable grace period (ShutdownTimeout, default 30 seconds) to finish current work and exit cleanly before being forcibly terminated -- well-behaved implementations check the token frequently and pass it into any awaited operations (Task.Delay, HTTP calls, database queries) so cancellation propagates correctly rather than the service ignoring shutdown signals.
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    while (!stoppingToken.IsCancellationRequested) {
        try {
            await DoWorkAsync(stoppingToken);
            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
        } catch (OperationCanceledException) {
            break;  // expected during graceful shutdown
        }
    }
}
Real-world example
A containerized worker correctly handles Kubernetes' SIGTERM-then-SIGKILL shutdown sequence by respecting the CancellationToken throughout, finishing its current batch within the grace period instead of being abruptly killed mid-processing.
Likely follow-ups
  • How do you configure the ShutdownTimeout grace period?
  • What happens if ExecuteAsync ignores the CancellationToken entirely?
Related topics