skip to content

In an ASP.NET Core BackgroundService, how should ExecuteAsync use its stoppingToken, and what happens at shutdown when the loop ignores it?

level: middleimportance: must knowfreq 55%

answer

  1. cancelled when StopAsync is called
  2. pass it to every await
  3. Task.Delay(period, stoppingToken)
  4. OperationCanceledException at stop is not a fault
  5. HostOptions.ShutdownTimeout, 30 s default

basics

~20 s

stoppingToken is cancelled when the host calls StopAsync, so the loop checks it and passes it to every awaited call. A loop that ignores it keeps running until the shutdown timeout, then is cut off mid-work when the process exits.

solid answer

~40 s

The base class cancels `stoppingToken` as the first step of `BackgroundService.StopAsync`, then waits for `ExecuteAsync` to finish. The loop should test `stoppingToken.IsCancellationRequested` in its condition and pass the token into every awaited call, such as `Task.Delay(period, stoppingToken)`, HTTP calls and EF Core queries, so a wait or I/O ends at once. The `OperationCanceledException` that follows is the normal way out; the host does not log it as a failure when it is stopping. If the loop ignores the token, or blocks with `Thread.Sleep`, `StopAsync` waits only until the host's shutdown token fires (`HostOptions.ShutdownTimeout`, 30 seconds by default). Then the host moves on, the process exits, and the iteration is abandoned half-done.

code

csharp · 16 lines
csharp
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        try
        {
            await readings.ImportPendingAsync(stoppingToken);
        }
        catch (Exception ex) when (ex is not OperationCanceledException)
        {
            logger.LogError(ex, "Meter import failed; retrying next cycle");
        }

        await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
    }
}

go deeper

for a junior

Recall that stoppingToken fires at shutdown and must be passed to Task.Delay and every other awaited call inside the loop.

for a middle

Explain what BackgroundService.StopAsync does step by step, why cancellation is cooperative, and how the host tells a clean cancellation from a real failure.

for a senior

Demonstrate shutdown design: per-iteration catch filters, work units that fit the shutdown window, and aligning the host's timeout with the orchestrator's grace period.

for a principal

Weigh how much in-flight work an app may lose at shutdown, and when that budget pushes long jobs out of the web process into resumable or durable processing.

## Where stoppingToken comes from `BackgroundService` owns a `CancellationTokenSource`. When the host starts the service, `StartAsync` links that source to the start-up token and passes its token to `ExecuteAsync(CancellationToken stoppingToken)`. When the app shuts down (Ctrl+C, SIGTERM from an orchestrator, a call to stop the application), the host calls every hosted service's `StopAsync`, and the base implementation: 1. cancels the token source, which flips `stoppingToken`; 2. awaits `ExecuteTask`, the task running your `ExecuteAsync`, with `WaitAsync` on the host's shutdown token; 3. returns either when your method finishes or when that shutdown token fires, whichever comes first. The shutdown token is the host's: `HostOptions.ShutdownTimeout`, 30 seconds unless configured. Cancellation in .NET is **cooperative**: nothing forcibly stops your loop. If the code never looks at the token, the cancel request goes unanswered. ## Using the token correctly - Put it in the loop condition: `while (!stoppingToken.IsCancellationRequested)`. - **Pass it to every awaited call**: `Task.Delay(period, stoppingToken)`, `PeriodicTimer.WaitForNextTickAsync(stoppingToken)`, `HttpClient.GetAsync(uri, stoppingToken)`, `ToListAsync(stoppingToken)` and `SaveChangesAsync(stoppingToken)` in EF Core. An await without it can sit for its full duration after shutdown starts. - Let the resulting `OperationCanceledException` escape, or catch it and return. Do not swallow it inside a catch-all that logs it as an error and loops again. - In a catch-all around one iteration, filter it out: `catch (Exception ex) when (ex is not OperationCanceledException)`. - Avoid synchronous blocking (`Thread.Sleep`, `.Result`, `.Wait()`): a blocked thread cannot react to the token. ## How the host treats a cancelled loop When `ExecuteAsync` ends with an `OperationCanceledException` for its own token, the task running it ends up cancelled. The host checks three things: the application is stopping, the task is cancelled, and the exception is an `OperationCanceledException`. When all three hold, it returns quietly. The same exception thrown while the app is **not** stopping is a real fault: the host logs it and, under the default `BackgroundServiceExceptionBehavior.StopHost`, stops the app. ## What happens when the token is ignored | Loop behaviour | Shutdown outcome | |---|---| | checks the token and passes it to awaits | ends within milliseconds, clean log | | checks the condition but awaits `Task.Delay(5 min)` without the token | sits in the delay; `StopAsync` waits until the shutdown timeout | | blocks with `Thread.Sleep` or a CPU loop | same wait, then the process exits underneath it | | finishes the current item, then exits on the next check | clean, if one item fits inside the shutdown timeout | After the timeout, `StopAsync` returns, the host completes shutdown and the process exits. Whatever the loop was doing (half a batch of invoice reminders, an uncommitted transaction) is cut off. In a container the orchestrator may also kill the process once its own grace period ends, which can be shorter than the host's timeout. ## One budget for every service The shutdown token is created once, when the host's `StopAsync` begins, with `CancelAfter(HostOptions.ShutdownTimeout)`. Every hosted service's `StopAsync` receives that same token, so the 30 seconds is a **shared** budget, not a per-service allowance: 1. the web server's hosted service, registered last, stops first and stops accepting requests; 2. your hosted services stop in reverse registration order, one after another by default; 3. a slow loop early in that sequence eats time that later services needed for their own clean stop. One loop that ignores its token can therefore leave every service after it with no time at all. ## Designing an iteration to stop well - Keep each unit of work small enough to finish or roll back inside the shutdown window. - Make the work restartable: record progress so the next process resumes rather than repeats. - Decide per call whether the token applies: an idempotent read can be cancelled; a short final write may deserve `CancellationToken.None` so the record is not left half-written. The `dotnet new worker` template's `Worker` class shows the minimal shape: `while (!stoppingToken.IsCancellationRequested)` with `await Task.Delay(1000, stoppingToken)` in the body.

  • Why should a catch-all inside the loop filter out OperationCanceledException?
    Without the filter, the cancellation thrown by `Task.Delay(..., stoppingToken)` or an EF Core call is caught, logged as an error and the loop goes round again. The next await throws again, so shutdown is noisy and only ends when the condition is checked. With `when (ex is not OperationCanceledException)` the exception leaves `ExecuteAsync`, and the host treats it as a normal stop.
  • If one unit of work needs about a minute, how do you keep it from being cut off at shutdown?
    Either make it resumable, recording progress so the next process continues, or raise `HostOptions.ShutdownTimeout` and the orchestrator's grace period together. Raising only the host's value does not help when the container is killed first. Splitting the unit into smaller committed steps is usually the more robust answer.

stoppingToken is the closing-time announcement in a library: readers who listen pack up and leave, but someone wearing headphones keeps reading until the caretaker locks the doors at the fixed hour, mid-page.

  • The host aborts the thread running ExecuteAsync as soon as shutdown starts
  • Checking IsCancellationRequested in the while condition is enough on its own
  • An OperationCanceledException at shutdown means the background service crashed
  • StopAsync waits for ExecuteAsync forever, however long it takes
  • Catch every exception in the loop, including OperationCanceledException, and keep going