skip to content

In ASP.NET Core, how do you run code when the app starts and when it shuts down, and how can code request a graceful stop?

level: juniorimportance: should knowfreq 40%

answer

  1. three CancellationToken properties
  2. app.Lifetime or inject the service
  3. Register takes a synchronous Action
  4. StopApplication starts graceful shutdown
  5. IApplicationLifetime is the obsolete name

basics

~10 s

Use IHostApplicationLifetime (app.Lifetime in Program.cs): register callbacks on its ApplicationStarted, ApplicationStopping and ApplicationStopped cancellation tokens. Calling StopApplication() triggers ApplicationStopping and the same graceful shutdown that Ctrl+C or SIGTERM starts.

solid answer

~40 s

`IHostApplicationLifetime` is a singleton the host registers; `WebApplication` exposes it as `app.Lifetime`, and any class or Minimal API handler can inject it. It has three `CancellationToken` properties used as events: `ApplicationStarted` fires once the host, including Kestrel, has fully started; `ApplicationStopping` fires when a graceful shutdown begins, and shutdown blocks until its callbacks finish; `ApplicationStopped` fires when shutdown is complete, and the app does not exit until those callbacks finish. You attach code with `token.Register(() => ...)`, which takes a synchronous `Action`, so an `async` lambda becomes fire-and-forget. `StopApplication()` cancels `ApplicationStopping` and so starts the normal shutdown: in-flight requests drain, hosted services stop, then `ApplicationStopped`. The older `IApplicationLifetime` in `Microsoft.AspNetCore.Hosting` is obsolete.

code

csharp · 14 lines
csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Lifetime.ApplicationStarted.Register(() => app.Logger.LogInformation("Ticket API ready"));
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Draining seat purchases"));
app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Stopped"));

app.MapPost("/admin/stop", (IHostApplicationLifetime lifetime) =>
{
    lifetime.StopApplication();   // graceful: same path as SIGTERM
    return Results.Accepted();
}).RequireAuthorization("Admins");

app.Run();

go deeper

for a junior

Recall the three tokens on IHostApplicationLifetime, that app.Lifetime exposes it, and that Register attaches code to each moment.

for a middle

Explain when each token fires, that callbacks are synchronous and block their phase, and what StopApplication sets in motion.

for a senior

Spot async-void callbacks and slow stopping hooks that delay draining, and move real cleanup into hosted services the host awaits.

for a principal

Decide which lifecycle work belongs in callbacks, hosted services or the platform, so instances start and stop predictably across a fleet.

## The service and its three tokens ASP.NET Core apps run inside the .NET **Generic Host**, which registers `IHostApplicationLifetime` (namespace `Microsoft.Extensions.Hosting`) as a singleton. In `Program.cs`, `WebApplication` exposes it as **`app.Lifetime`**; elsewhere you inject it through the constructor or as a Minimal API handler parameter. The interface is small: | Member | Kind | When it fires | |---|---|---| | `ApplicationStarted` | `CancellationToken` | the host has fully started: hosted services started, Kestrel listening | | `ApplicationStopping` | `CancellationToken` | a graceful shutdown is starting; shutdown blocks until these callbacks complete | | `ApplicationStopped` | `CancellationToken` | graceful shutdown is complete; the app does not exit until these callbacks complete | | `StopApplication()` | method | requests a graceful shutdown | The tokens are not cancelled because something failed; cancellation is simply how the host **signals** the moment. You subscribe with `CancellationToken.Register`. ## Registering callbacks ```csharp var app = builder.Build(); app.Lifetime.ApplicationStarted.Register(() => app.Logger.LogInformation("Box office open: ticket API is accepting requests")); app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Box office closing: draining seat purchases")); app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Box office closed")); ``` Points that interviewers probe: - **Callbacks are synchronous.** `Register` takes an `Action`. Writing `Register(async () => await FlushAsync())` compiles into an `async void` delegate: the host considers the callback done at its first `await`, so the flush may never finish. Do short synchronous work here, or put asynchronous cleanup in a hosted service's `StopAsync`, which the host awaits. - **Callbacks block the phase.** A slow `ApplicationStopping` callback delays everything after it, including the server's drain. - **Exceptions are logged, not thrown.** The host catches an exception from a callback and logs it as an error rather than crashing shutdown. - **Registering late still works.** Registering on a token that has already fired runs the callback immediately. ## What fires the tokens 1. `ApplicationStarted` is signalled by the host after every hosted service, including the web server, has started. The console logger then writes `Application started. Press Ctrl+C to shut down.` under the `Microsoft.Hosting.Lifetime` category. 2. `ApplicationStopping` is signalled by `StopApplication()`. The console lifetime calls it on **Ctrl+C (SIGINT), SIGQUIT and SIGTERM**, and on Linux and macOS it cancels the default process termination so the app can stop cleanly; the log reads `Application is shutting down...`. 3. `ApplicationStopped` is signalled after the server has drained and every hosted service has stopped. ## Requesting a stop from code `StopApplication()` does not kill anything. It starts the same graceful path a signal would: `ApplicationStopping` callbacks run, `app.Run()` stops waiting and calls the host's `StopAsync`, Kestrel stops accepting connections and drains in-flight requests, hosted services stop, `ApplicationStopped` fires, and `app.Run()` returns. Typical uses: - an admin endpoint or a failed critical background check that should take the instance out cleanly; - a one-off job hosted as a web app that should exit when done. Compare it with `Environment.Exit`, which terminates the process without draining requests or awaiting hosted services. ## History `IApplicationLifetime` in `Microsoft.AspNetCore.Hosting` is the ASP.NET Core 2.x interface. It is marked `[Obsolete]` and recommends `IHostApplicationLifetime`; use it only when reading old code.

  • Why is ApplicationStopping.Register(async () => await queue.FlushAsync()) a bug?
    `Register` accepts an `Action`, so the async lambda becomes `async void`. The callback returns at its first `await`, the host treats it as finished and carries on stopping, and the flush can be cut off when the process exits. Do asynchronous cleanup in an `IHostedService.StopAsync`, which the host awaits with the shutdown token.
  • How is StopApplication() different from Environment.Exit(0) inside a request?
    `StopApplication()` only signals `ApplicationStopping` and returns; the current request can still complete, Kestrel drains other in-flight requests, hosted services stop and `ApplicationStopped` fires before `app.Run()` returns. `Environment.Exit` ends the process without that drain, so in-flight requests are cut off.

  • ApplicationStarted fires as soon as builder.Build() returns.
  • StopApplication() kills the process immediately, like Environment.Exit.
  • An async lambda passed to Register is awaited by the host.
  • IApplicationLifetime from Microsoft.AspNetCore.Hosting is the current interface to inject.
  • ApplicationStopping only fires on Ctrl+C, not when the container sends SIGTERM.