ASP.NET Core Interview Question #166
What is graceful shutdown in ASP.NET Core?
Logging, Error Handling & Background Services Mid-Level Intermediate
Quick Interview Answer
Graceful shutdown allows the application to stop accepting new work and gives in-progress operations and hosted services an opportunity to finish or cancel cleanly.
Detailed Explanation
Graceful shutdown allows the application to stop accepting new work and gives in-progress operations and hosted services an opportunity to finish or cancel cleanly.
The host signals cancellation and invokes hosted-service shutdown behavior. Well-designed background workers observe cancellation tokens and avoid indefinitely blocking shutdown.
External infrastructure such as containers and process managers should also provide enough termination time for the application to shut down cleanly.
Code Example
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
try
{
await RunWorkerAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
// Expected during graceful shutdown.
}
}