.NET › Generic Host
How does the Generic Host manage the application's startup and shutdown lifecycle, including handling OS signals like SIGTERM?
AdvancedAnswer
The host registers signal handlers (via IHostApplicationLifetime and platform-specific mechanisms) for graceful shutdown signals -- SIGTERM/SIGINT on Linux/macOS, Ctrl+C or service stop on Windows -- triggering ApplicationStopping, then calling StopAsync on all registered IHostedService instances (respecting the configured ShutdownTimeout grace period) before ApplicationStopped fires, ensuring resources are cleaned up and in-flight work has a chance to complete before the process actually terminates, which is especially important in container orchestrators that send SIGTERM before forcibly killing a container.
public class MyService(IHostApplicationLifetime lifetime) : IHostedService {
public Task StartAsync(CancellationToken ct) {
lifetime.ApplicationStarted.Register(() => Console.WriteLine("Started"));
lifetime.ApplicationStopping.Register(() => Console.WriteLine("Stopping..."));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}Real-world example A Kubernetes-hosted service relies on the Generic Host correctly handling SIGTERM (sent by Kubernetes before a pod is force-killed) to gracefully finish in-flight requests within the pod's terminationGracePeriodSeconds window, avoiding abruptly dropped connections during routine pod rescheduling.