Signals and graceful shutdown
suggest changeLong-running programs (servers, workers, daemons, CLI tools that process big files) don't usually end by reaching the end of Main. They get stopped from outside: a user presses Ctrl+C, docker stop or Kubernetes sends SIGTERM, systemd stops a service, Windows shuts down.
A graceful shutdown means that when this happens the program:
- stops accepting new work
- finishes (or cleanly abandons) work in progress
- flushes buffers, saves state, closes files and connections
- exits within a reasonable time, with a meaningful exit code
The alternative is losing data that was only in memory, leaving half-written files and temp files behind, or leaving a database transaction or message unacknowledged.
.NET gives you three tools for this:
Console.CancelKeyPress: the classicCtrl+C/Ctrl+Breakevent, works everywherePosixSignalRegistration(.NET 6+): handleSIGINT,SIGTERM,SIGQUIT,SIGHUPand other signals- the Generic Host (
Microsoft.Extensions.Hosting), which wires all of this up for you and turns it into aCancellationToken
Examples below were run on Linux with .NET 10.
Signals in a nutshell
On Unix (Linux, macOS) the OS tells a process to stop by sending it a signal. The ones that matter for shutdown:
| Signal | Number | Sent by | Default action |
|---|---|---|---|
SIGINT |
2 | Ctrl+C in a terminal |
terminate |
SIGTERM |
15 | kill <pid>, docker stop, Kubernetes, systemd |
terminate |
SIGQUIT |
3 | Ctrl+\ in a terminal |
terminate + core dump |
SIGHUP |
1 | terminal closed; by convention also "reload config" | terminate |
SIGKILL |
9 | kill -9, after a grace period expires |
terminate, can't be caught |
A program can catch the first four and do something else instead of the default action. SIGKILL (and SIGSTOP) can't be caught, blocked or ignored. That's why all orchestrators follow the same pattern: send SIGTERM, wait for a grace period (10 seconds for docker stop, 30 seconds by default in Kubernetes), then send SIGKILL. Your cleanup has to fit into that window.
When a process is killed by a signal, shells report the exit code as 128 + signal number: 130 for SIGINT, 143 for SIGTERM, 137 for SIGKILL.
Windows has no signals. Console programs get console control events instead: CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT (console window closed), CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT. .NET maps these onto the same APIs, as shown below.
Console.CancelKeyPress
Console.CancelKeyPress is raised when the user presses Ctrl+C or Ctrl+Break. On Unix it's raised for SIGINT and SIGQUIT. Setting e.Cancel = true tells the runtime not to terminate the process:
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine($"Got {e.SpecialKey}, ignoring it");
e.Cancel = true;
};
for (int i = 0; i < 3; i++)
{
Console.WriteLine("working");
await Task.Delay(1000);
}
Console.WriteLine("done");
$ ./app
working
working
^CGot ControlC, ignoring it
working
done
e.SpecialKey is ConsoleSpecialKey.ControlC or ConsoleSpecialKey.ControlBreak (Ctrl+Break on Windows, SIGQUIT on Unix).
If you leave e.Cancel as false, the handler runs and then the process is terminated immediately. Code after the current line in Main doesn't run, finally blocks don't run, and on Unix the exit code is 130:
Console.CancelKeyPress += (sender, e) => Console.WriteLine($"Got {e.SpecialKey}");
Thread.Sleep(5000);
Console.WriteLine("done");
$ ./app
^CGot ControlC
$ echo $?
130
Don't do the actual cleanup inside the handler. It runs on a separate thread while your main code keeps running, and if it doesn't cancel, the process dies as soon as it returns. The right job for the handler is to tell the rest of the program to stop, and let the main code do the cleanup on its normal path.
Turning Ctrl+C into a CancellationToken
The standard pattern is to translate the signal into a CancellationToken. All async .NET APIs accept one, so cancellation flows naturally through the program (see Cancellation and timeouts for the token basics):
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true; // don't kill the process, we'll exit on our own
Console.WriteLine("Ctrl+C: stopping...");
cts.Cancel();
};
try
{
await RunAsync(cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
Console.WriteLine("Cancelled");
}
finally
{
Console.WriteLine("Cleaning up");
}
return cts.IsCancellationRequested ? 130 : 0;
static async Task RunAsync(CancellationToken ct)
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"step {i}");
await Task.Delay(1000, ct);
}
}
$ ./app
step 1
step 2
^CCtrl+C: stopping...
Cancelled
Cleaning up
$ echo $?
130
Points to note:
cts.Cancel()is thread-safe, so it's fine to call it from the handler thread.Task.Delay(1000, ct)throwsOperationCanceledExceptionas soon as the token is cancelled, so the program reacts immediately instead of finishing the current wait.- The
when (cts.IsCancellationRequested)filter makes sure we only swallow cancellations caused by our shutdown, not, say, anHttpClienttimeout. - Returning 130 tells scripts that the program was interrupted rather than completed. Return 0 if a cancelled run is a normal outcome for your tool.
CPU-bound loops that don't call async APIs should check ct.ThrowIfCancellationRequested() or ct.IsCancellationRequested regularly, for example once per processed record.
Second Ctrl+C forces exit
If cleanup takes a while (or hangs), users expect a second Ctrl+C to kill the program. Cancel only the first time and let the second one through:
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
if (cts.IsCancellationRequested)
{
Console.WriteLine("Second Ctrl+C: exiting immediately");
return; // e.Cancel stays false: the process terminates
}
e.Cancel = true;
Console.WriteLine("Shutting down, press Ctrl+C again to force");
cts.Cancel();
};
try
{
await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (OperationCanceledException) { }
Console.WriteLine("slow cleanup");
await Task.Delay(5000);
Console.WriteLine("cleanup done");
$ ./app
^CShutting down, press Ctrl+C again to force
slow cleanup
^CSecond Ctrl+C: exiting immediately
$ echo $?
130
PosixSignalRegistration
Console.CancelKeyPress doesn't cover SIGTERM, which is what containers and service managers send. For that, use PosixSignalRegistration from System.Runtime.InteropServices (.NET 6 and later):
using System.Runtime.InteropServices;
using var cts = new CancellationTokenSource();
void OnSignal(PosixSignalContext ctx)
{
ctx.Cancel = true; // skip the default action (terminating the process)
Console.WriteLine($"Received {ctx.Signal}");
cts.Cancel();
}
using var sigInt = PosixSignalRegistration.Create(PosixSignal.SIGINT, OnSignal);
using var sigTerm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, OnSignal);
using var sigQuit = PosixSignalRegistration.Create(PosixSignal.SIGQUIT, OnSignal);
Console.WriteLine($"pid {Environment.ProcessId}, waiting for a signal");
try
{
await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (OperationCanceledException) { }
Console.WriteLine("shut down cleanly");
$ ./app &
pid 714, waiting for a signal
$ kill 714
Received SIGTERM
shut down cleanly
How it works:
Createreturns a registration object. The handler stays active until it's disposed. Keep a reference to it for as long as you want the handler (hereusing vardoes that). An unreferenced registration can be garbage-collected, which removes the handler.- The handler receives a
PosixSignalContextwith theSignaland aCancelproperty.Cancel = truesuppresses the default action. If you leave itfalse, the handler runs and then the default action (usually termination) follows. - Multiple registrations for the same signal are allowed; all of them run.
- Handlers run on a thread-pool thread, not the main thread.
On Windows only SIGINT, SIGQUIT, SIGHUP and SIGTERM are supported, mapped from console control events:
| PosixSignal | Windows event |
|---|---|
SIGINT |
CTRL_C_EVENT |
SIGQUIT |
CTRL_BREAK_EVENT |
SIGHUP |
CTRL_CLOSE_EVENT (console window closed) |
SIGTERM |
CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT |
Other signals throw PlatformNotSupportedException on Windows. Note that Windows doesn't let a program survive close, logoff and shutdown events: it gives the process a few seconds and then terminates it regardless of Cancel.
SIGHUP: reloading configuration
Daemons traditionally use SIGHUP as "re-read your config file" (nginx and many others do this). The default action for SIGHUP is termination, so you must set Cancel = true:
using System.Runtime.InteropServices;
int reloads = 0;
using var hup = PosixSignalRegistration.Create(PosixSignal.SIGHUP, ctx =>
{
ctx.Cancel = true;
Console.WriteLine($"reload #{++reloads}");
// re-read the config file here
});
await Task.Delay(Timeout.Infinite);
$ kill -HUP 742
reload #1
$ kill -HUP 742
reload #2
If you use Microsoft.Extensions.Configuration with reloadOnChange: true, file changes are picked up automatically and you may not need this.
Other signals
The PosixSignal enum only names the portable signals. You can handle any other signal by casting its raw number, for example SIGUSR1, which is 10 on Linux (and 30 on macOS, so the number is platform-specific):
using var usr1 = PosixSignalRegistration.Create((PosixSignal)10, ctx =>
{
ctx.Cancel = true;
Console.WriteLine($"signal {(int)ctx.Signal}: dumping stats");
});
Don't forget ctx.Cancel = true here either. The default action of SIGUSR1 is to terminate the process, and without it the program prints the message and dies with exit code 138 (128 + 10).
AppDomain.ProcessExit
AppDomain.CurrentDomain.ProcessExit is raised when the process is exiting normally: Main returned or Environment.Exit was called:
AppDomain.CurrentDomain.ProcessExit += (_, _) => Console.WriteLine("ProcessExit");
if (args.Length > 0)
{
Environment.Exit(3);
}
Console.WriteLine("done");
$ ./app
done
ProcessExit
$ ./app x
ProcessExit
$ echo $?
3
It is not a signal handler. It doesn't run when the process is killed by an unhandled SIGINT, SIGKILL or a crash. In .NET 10 the runtime also stopped handling SIGTERM by itself (earlier versions raised ProcessExit on SIGTERM), so an app with no handlers is simply terminated with exit code 143:
$ ./app &
$ kill %1
[1]+ Terminated ./app
Older code often used ProcessExit plus a ManualResetEvent as a poor man's SIGTERM handler. Use PosixSignalRegistration or the Generic Host instead. Keep ProcessExit for last-chance, quick, synchronous work like flushing a log.
The Generic Host
If your app uses Microsoft.Extensions.Hosting (worker services, ASP.NET Core and anything created with dotnet new worker), shutdown handling is already done for you. The default ConsoleLifetime registers for SIGINT, SIGQUIT and SIGTERM, cancels the signal's default action, and starts an orderly shutdown:
IHostApplicationLifetime.ApplicationStoppingis triggered.StopAsyncis called on every hosted service in reverse registration order. For aBackgroundServicethis cancels thestoppingTokenpassed toExecuteAsyncand waits for it to finish.ApplicationStoppedis triggered andRunAsyncreturns.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(5));
using var host = builder.Build();
var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping"));
lifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped"));
await host.RunAsync();
Console.WriteLine("host exited");
class Worker(ILogger<Worker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
int n = 0;
while (!stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Processing item {N}", ++n);
try
{
await Task.Delay(1000, stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
}
logger.LogInformation("Worker finishing, flushing state");
await Task.Delay(500); // e.g. save a checkpoint
logger.LogInformation("Worker done");
}
}
The project needs the Microsoft.Extensions.Hosting package (dotnet add package Microsoft.Extensions.Hosting). Sending SIGTERM (or pressing Ctrl+C) gives (a couple of startup log lines omitted):
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Worker[0]
Processing item 1
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
ApplicationStopping
info: Worker[0]
Worker finishing, flushing state
info: Worker[0]
Worker done
ApplicationStopped
host exited
The process exits with code 0, because shutdown was orderly.
Shutdown timeout
HostOptions.ShutdownTimeout (30 seconds by default) limits how long the host waits for hosted services to stop. If a service is still running when it expires, the host stops waiting, RunAsync returns and the process exits, killing the unfinished work. With the 5-second timeout above and a cleanup that takes 8 seconds, the output ends like this, without "Worker done":
info: Worker[0]
Worker finishing, flushing state
ApplicationStopped
host exited
Set ShutdownTimeout a bit shorter than the orchestrator's grace period (docker stop -t, Kubernetes terminationGracePeriodSeconds), so the host gets to finish its own shutdown sequence before SIGKILL arrives.
Besides code, the timeout can be set through the host configuration key shutdownTimeoutSeconds, for example with an environment variable, which is handy in a Dockerfile or Kubernetes manifest:
$ DOTNET_SHUTDOWNTIMEOUTSECONDS=20 ./app
An explicit Configure<HostOptions> in code takes precedence over it. Note that a "HostOptions" section in appsettings.json is not bound automatically; you'd have to bind it yourself with builder.Services.Configure<HostOptions>(builder.Configuration.GetSection("HostOptions")).
Stopping from inside the app
To shut down because of something the program itself decided (a fatal error, a one-shot job is done), call IHostApplicationLifetime.StopApplication(). It runs exactly the same sequence as a signal:
class OneShotJob(IHostApplicationLifetime lifetime) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await DoTheJobAsync(stoppingToken);
}
finally
{
lifetime.StopApplication();
}
}
private static Task DoTheJobAsync(CancellationToken ct) => Task.Delay(2000, ct);
}
Since .NET 6 an unhandled exception in ExecuteAsync also stops the host (BackgroundServiceExceptionBehavior.StopHost) instead of being silently ignored. Set Environment.ExitCode before stopping if the failure should be visible to the caller.
ASP.NET Core apps use the same host. When SIGTERM arrives Kestrel stops accepting connections and waits for in-flight requests within the shutdown timeout. Inject IHostApplicationLifetime there too, or use HttpContext.RequestAborted in long-running requests.
Running in Docker and Kubernetes
Signals only help if they reach your process. Common pitfalls:
- Use the exec form of
ENTRYPOINT:ENTRYPOINT ["dotnet", "MyApp.dll"]. The shell formENTRYPOINT dotnet MyApp.dllruns your app as a child of/bin/sh -c, which doesn't forwardSIGTERM. The app never hears it and getsSIGKILLed after the grace period. - Wrapper scripts should end with
exec dotnet MyApp.dll, so that the app replaces the shell. docker stopwaits 10 seconds by default; change it withdocker stop -t 30orstop_grace_periodin Compose.- In Kubernetes,
terminationGracePeriodSecondsdefaults to 30. The pod is removed from service endpoints at about the same timeSIGTERMis sent, so a web app may still receive a few requests during the first moments of shutdown. A short delay at the start ofApplicationStopping(or apreStophook) helps.
Sending signals from C#
Process.Kill() is not graceful: on Unix it sends SIGKILL, on Windows it calls TerminateProcess. The child gets no chance to clean up.
.NET has no API for sending other signals, but on Unix you can run the kill command:
using System.Diagnostics;
var child = Process.Start("./worker")!;
await Task.Delay(3000);
// ask nicely first
Process.Start("kill", ["-TERM", child.Id.ToString()])!.WaitForExit();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await child.WaitForExitAsync(timeout.Token);
}
catch (OperationCanceledException)
{
child.Kill(entireProcessTree: true); // didn't stop in time
}
Console.WriteLine($"worker exited with {child.ExitCode}");
This is the same SIGTERM, wait, SIGKILL sequence orchestrators use. See Running OS commands for more about Process.
Tips
- Signal handlers should only signal. Set a flag or cancel a
CancellationTokenSource; do the real cleanup on the main code path, wheretry/finallyandusingwork as usual. - Pass the token everywhere. Graceful shutdown is only as fast as the slowest piece of code that ignores the
CancellationToken. - Bound your cleanup. Use a timeout for the shutdown work itself (for example
new CancellationTokenSource(TimeSpan.FromSeconds(5))for final flushes) so a hung network call can't block exit untilSIGKILL. - Make work restartable. You can't catch
SIGKILL, power loss or a crash. Graceful shutdown reduces lost work but doesn't replace idempotent processing, transactions and atomic file writes (write to a temp file, then rename). - Prefer the Generic Host for services. It handles
SIGINT,SIGTERMandSIGQUIT, timeouts and ordering for you; hand-written handlers are for small console tools. - Test it. Run the app, send
kill -TERM <pid>(or pressCtrl+C) and check the logs and exit code. Shutdown paths are rarely exercised and often broken.