skip to content

What changed in .NET 10 about how BackgroundService.ExecuteAsync starts, and where should ASP.NET Core start-up work that must finish before requests go?

level: middleimportance: should knowfreq 32%

answer

  1. code before the first await
  2. whole ExecuteAsync now in Task.Run
  3. StartAsync still blocks start-up
  4. IHostedLifecycleService.StartingAsync (.NET 8)
  5. server registered after your services

basics

~20 s

In .NET 10 BackgroundService runs all of ExecuteAsync inside Task.Run, so code before the first await no longer blocks start-up. Work that must finish before requests arrive goes in an overridden StartAsync or IHostedLifecycleService.StartingAsync instead.

solid answer

~40 s

Up to .NET 9, `BackgroundService.StartAsync` called `ExecuteAsync` directly, so everything before its first `await` ran on the start-up path and held up the next hosted service and the web server. In .NET 10 the base class runs **all** of `ExecuteAsync` through `Task.Run` and returns at once, so nothing in it delays start-up. Code that relied on that accidental blocking, such as a cache warm-up at the top of `ExecuteAsync`, now races the first requests. Work that must complete first belongs in `StartAsync`, either a plain `IHostedService` or an override that awaits the work and then calls `base.StartAsync`, or in `IHostedLifecycleService.StartingAsync` (added in .NET 8). `WebApplicationBuilder.Build()` registers the web server's hosted service after yours, so with the default sequential start your `StartAsync` finishes before Kestrel listens.

code

csharp · 18 lines
csharp
public sealed class TariffCacheService(TariffCache cache) : BackgroundService
{
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        // Runs on the start-up path: Kestrel listens only after this completes.
        await cache.LoadAsync(cancellationToken);
        await base.StartAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(15));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            await cache.LoadAsync(stoppingToken);
        }
    }
}

go deeper

for a junior

Recall that ExecuteAsync is for the loop, while work that must finish before the app serves requests belongs in StartAsync.

for a middle

Explain the .NET 10 Task.Run change, the IHostedLifecycleService hooks and their order, and why your StartAsync finishes before the server listens.

for a senior

Audit upgrades from .NET 8 or 9 for warm-up code that relied on blocking in ExecuteAsync, and bound start-up work with its own timeout since StartupTimeout is infinite.

for a principal

Weigh blocking start-up on warm-up against readiness-gated traffic, and which of the two the deployment platform's health probes support better.

## The old behaviour Before .NET 10, `BackgroundService.StartAsync` invoked `ExecuteAsync(token)` directly and stored the returned task. An `async` method runs synchronously until its first incomplete `await`, so everything above that point ran **inside** the host's start-up sequence: - a slow synchronous call at the top of `ExecuteAsync` delayed every hosted service registered after it; - in a web app, that included the server, so the app did not listen until the call returned; - a loop with no real `await` (for example one that only polled synchronously) could block start-up forever. The official hosted-services page still describes this ("no further services are started until ExecuteAsync becomes asynchronous"); the .NET 10 source and breaking-change notice supersede it. ## The .NET 10 behaviour In .NET 10, `StartAsync` does `_executeTask = Task.Run(() => ExecuteAsync(_stoppingCts.Token), _stoppingCts.Token)` and returns `Task.CompletedTask`. All of `ExecuteAsync`, including the part before the first `await`, runs on a thread-pool thread. The consequences: 1. A `BackgroundService` can no longer hold up start-up, which removes a common pitfall. 2. Code that **depended** on that blocking now runs concurrently with the server: requests can arrive before the warm-up at the top of `ExecuteAsync` has finished. ## Where blocking start-up work goes now The breaking-change notice lists the alternatives: | Place | When it runs | Blocks start-up? | |---|---|---| | constructor of the service | when the host resolves hosted services | yes, keep it small | | override `StartAsync`, await work, then `base.StartAsync` | in the hosted-service start sequence | yes | | plain `IHostedService.StartAsync` | in the hosted-service start sequence | yes | | `IHostedLifecycleService.StartingAsync` | before **any** hosted service's `StartAsync` | yes | | `IHostedLifecycleService.StartedAsync` | after **all** `StartAsync` calls, including the server's | yes, but requests may already be served | | `BackgroundService.ExecuteAsync` | on a thread-pool thread | no | `IHostedLifecycleService` arrived in .NET 8. It extends `IHostedService` with `StartingAsync`, `StartedAsync`, `StoppingAsync` and `StoppedAsync`; a `BackgroundService` can implement it as well. ## Why StartAsync runs before the server listens The host starts hosted services in registration order, one at a time unless `HostOptions.ServicesStartConcurrently` is set to true. `WebApplicationBuilder.Build()` adds the web server's own hosted service **after** all services you registered, so your `StartAsync` methods complete before Kestrel starts accepting connections. On shutdown the order reverses: the server stops first, then your services. Two rules keep this safe: - An exception in `StartingAsync`, `StartAsync` or `StartedAsync` aborts start-up and the app fails fast. - `HostOptions.StartupTimeout` defaults to infinite, so a hung warm-up hangs the deployment; give the work its own timeout. ## Spotting the upgrade bug After an upgrade to .NET 10, the symptom is a burst of errors or slow responses in the first seconds after each deployment, from requests that hit a cache or connection the background service has not prepared yet. Nothing fails at start-up, because start-up no longer waits. A readiness probe that only checks that the process responds will route traffic too early; the fix is to put the preparation back on the start-up path, or to make readiness depend on it. ## Migrating a .NET 8 or 9 service Move anything at the top of `ExecuteAsync` that must finish before traffic into a `StartAsync` override, and keep the loop itself in `ExecuteAsync`.

  • In which order does IHostedLifecycleService call its hooks relative to StartAsync and StopAsync?
    On start: every service's `StartingAsync`, then every `StartAsync`, then every `StartedAsync`, then the application-started notification. On stop, in reverse service order: `StoppingAsync`, then `StopAsync`, then `StoppedAsync`. An exception in a start hook aborts start-up.
  • What does HostOptions.ServicesStartConcurrently change, and why is it off by default?
    Set to true, the host starts hosted services in parallel instead of one after another, which can shorten start-up when several services do slow I/O in `StartAsync`. It is false by default, which keeps start-up in registration order; that order is what guarantees your services finish `StartAsync` before the web server's hosted service starts, and turning the option on gives that guarantee up.

  • In .NET 10, code before the first await in ExecuteAsync still blocks start-up
  • StartedAsync runs before Kestrel starts listening
  • HostOptions.StartupTimeout defaults to 30 seconds
  • IHostedLifecycleService replaces IHostedService and needs a separate registration call
  • Hosted services start in parallel by default

Assumes .NET 10: BackgroundService runs all of ExecuteAsync via Task.Run from 10 on, while .NET 8 and 9 ran the part before the first await on the start-up path; IHostedLifecycleService exists since .NET 8.