In ASP.NET Core 10, what happens to the whole app when a BackgroundService's ExecuteAsync throws an unhandled exception, and how should the loop be designed for it?
answer
- one loop can stop the web app
- HostOptions.BackgroundServiceExceptionBehavior
- StopHost default since .NET 6
- Ignore leaves a dead loop
- graceful stop, exit code 0 in 10
basics
~20 sThe host logs the exception and, under the default BackgroundServiceExceptionBehavior.StopHost, stops the application, so every endpoint goes down with the loop. Catch failures per iteration inside the loop and let only truly fatal errors escape.
solid answer
~40 sThe host awaits each `BackgroundService`'s `ExecuteTask`. When it faults outside shutdown, the host logs `BackgroundServiceFaulted` and, because `HostOptions.BackgroundServiceExceptionBehavior` defaults to `StopHost` (since .NET 6), logs `BackgroundServiceStoppingHost` and stops the application: a bug in a reminder loop takes the whole web app down. Setting `Ignore` keeps the app up but leaves the loop dead, a zombie nobody notices. In .NET 10 the stop is graceful and `app.Run()` returns normally, so the process exits with code 0 unless you set one, and a restart-on-failure policy may not fire. The design is a `try`/`catch` around each iteration that logs and continues, with `OperationCanceledException` filtered out. Keep `StopHost` for what is truly unrecoverable, and make that exit non-zero.
code
csharp · 21 linesprotected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await billing.PostPaymentsAsync(stoppingToken);
}
catch (TariffConfigurationException ex)
{
logger.LogCritical(ex, "Tariff configuration invalid; stopping");
Environment.ExitCode = 1;
throw;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Payment posting failed; next cycle retries");
}
}
}go deeper
Recall that an unhandled exception in a BackgroundService stops the whole app by default, so wrap each loop iteration in try/catch.
Explain the two BackgroundServiceExceptionBehavior values, what each logs, and why OperationCanceledException at shutdown is not treated as a fault.
Design for failure: per-iteration catch with back-off, deliberate escape for fatal errors, a non-zero exit code for the restart policy, and visibility when Ignore is chosen.
Judge whether a background loop's failure should take its web endpoints down with it, and when that coupling argues for running the loop in its own process.
## What the host does with a faulted loop When a `BackgroundService` starts, the host keeps a reference to its `ExecuteTask` and awaits it in the background. If that task ends with an exception, the host: 1. ignores it if the app is already stopping, the task is cancelled and the exception is an `OperationCanceledException` (a normal stop); 2. otherwise logs it as `BackgroundServiceFaulted` (event id 9) at error level; 3. checks `HostOptions.BackgroundServiceExceptionBehavior`. With **`StopHost`**, the default, it logs `BackgroundServiceStoppingHost` (event id 10) and calls `StopApplication()`; with **`Ignore`** it does nothing more. `StopApplication()` starts an ordinary graceful shutdown: the web server stops accepting requests and every hosted service is stopped. One throwing loop therefore takes down every endpoint the process serves. ## Why the default is StopHost Before .NET 6 the exception was lost: the loop died silently, nothing was logged, and the app kept serving traffic while its background work had stopped. .NET 6 changed this to log the exception and stop the host by default, on the reasoning that an unhandled exception signals a problem that needs attention. `Ignore` restores the old continue-running behaviour, though the exception is still logged now. | Setting | Logged | App keeps serving | Loop keeps running | |---|---|---|---| | `StopHost` (default) | yes | no, graceful shutdown | no | | `Ignore` | yes | yes | no, it is dead | Neither value restarts the loop. Nothing in the host retries `ExecuteAsync`. ## The exit-code trap in .NET 10 The stop is a **graceful** one. In .NET 10, `app.Run()` / `RunAsync()` returns normally after it, so a top-level `Program.cs` exits with code 0 unless something set `Environment.ExitCode`. An orchestrator or service manager that restarts only on failure sees a clean exit and may leave the app down. The .NET worker-service guidance for Windows services makes the same point and exits with a non-zero code in its catch block. A change in the .NET 11 previews makes `RunAsync` throw in this case, but that is not .NET 10 behaviour. ## Designing the loop - **Catch per iteration.** Wrap the body of one cycle in `try`/`catch (Exception ex) when (ex is not OperationCanceledException)`, log, and continue. A transient database or SMTP error should cost one cycle, not the app. - **Back off.** After repeated failures, wait longer before the next attempt instead of hammering a broken dependency. - **Let fatal errors escape on purpose.** A misconfiguration that will fail every cycle is better surfaced by stopping, and with a non-zero exit code, e.g. `Environment.ExitCode = 1` before rethrowing, so the platform restarts or alerts. - **Keep `StopHost`.** Switching to `Ignore` to keep the site up trades a visible outage for an invisible one; if you choose it, expose the loop's state, for example through a health check that inspects `ExecuteTask`. - **Fail in `StartAsync` for start-up problems.** An exception thrown from `StartAsync` aborts start-up, which fails fast and loudly. ## Recognising it in the logs The sequence comes from the `Microsoft.Extensions.Hosting.Internal.Host` category: 1. an error entry, event id 9 (`BackgroundServiceFaulted`), message "BackgroundService failed", with the exception attached; 2. a critical entry, event id 10 (`BackgroundServiceStoppingHost`), saying `BackgroundServiceExceptionBehavior` is `StopHost`, the host is stopping, and that with `Ignore` the service would not be restarted; 3. the ordinary graceful-shutdown messages. An incident that looks like "the API went down for no reason" often starts with entry 1 from a loop nobody was watching. ## Configuring it `builder.Services.Configure<HostOptions>(o => o.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore);` changes the behaviour for every background service in the host; there is no per-service setting, another reason to handle errors inside each loop.
- Does BackgroundServiceExceptionBehavior.Ignore restart the failed loop?No. `Ignore` only stops the host from shutting down; the exception is still logged and `ExecuteTask` stays faulted. The loop is gone until the process restarts. If you need it to keep running, catch inside the loop, or expose its state through a health check so the platform can recycle the instance.
- Can you choose StopHost for one background service and Ignore for another?Not with the option: `BackgroundServiceExceptionBehavior` lives on `HostOptions` and applies to every `BackgroundService` in the host. Per-service policy is written in each loop, by catching what that loop can survive and letting the rest escape.
- An exception in ExecuteAsync is swallowed and only that loop stops
- The host restarts a BackgroundService after it throws
- BackgroundServiceExceptionBehavior.Ignore stops the exception from being logged
- When StopHost fires, the process always exits with a non-zero code
- Set Ignore so the app stays up; the loop will recover by itself
Assumes ASP.NET Core 10 on .NET 10: StopHost has been the default since .NET 6, and in 10 the host's RunAsync still completes normally after such a stop; the .NET 11 previews change that.