Explains IHostedService and BackgroundService in .NET 10: registration with AddHostedService, the start-up and shutdown order, ExecuteAsync and its stopping token, the .NET 10 change that runs all of ExecuteAsync in the background, IHostedLifecycleService, the Worker Service template, and in-process versus separate workers.
A hosted service is a class the .NET Generic Host starts and stops with the application. IHostedService gives you StartAsync and StopAsync. BackgroundService is the base class most people use: you override one method, ExecuteAsync(CancellationToken stoppingToken), and loop until the token is cancelled at shutdown. You register it with AddHostedService<T>(), as a singleton, so you use IServiceScopeFactory to get scoped services like a DbContext. In .NET 10 the whole of ExecuteAsync runs on a background task, so it doesn't delay start-up. On shutdown the host cancels the token and waits up to HostOptions.ShutdownTimeout (30 seconds by default). The Worker Service template is the same host without a web server, for queue consumers and scheduled jobs.
The trade-off: running inside your API is simple, but a separate worker scales and fails independently.
"A hosted service is anything that should run for the lifetime of the app, not per request: consuming a queue, refreshing a cache, sending scheduled emails. The contract is
IHostedServicewithStartAsyncandStopAsync. The host callsStartAsyncon each one in registration order during start-up, andStopAsyncin reverse order on shutdown. In practice I derive fromBackgroundService, which implements that interface for me. I overrideExecuteAsync(CancellationToken stoppingToken)and write a loop that runs until the token is cancelled.There are a few lifecycle details that matter. In ASP.NET Core, hosted services start before Kestrel starts accepting requests, so a slow
StartAsyncdelays your app becoming ready. Before .NET 10, the synchronous part ofExecuteAsync, everything before the firstawait, ran on the start-up path and could block the whole app. In .NET 10 the host runs all ofExecuteAsyncas a background task, so that trap is gone. If you genuinely need code to run during start-up, you put it inStartAsyncor useIHostedLifecycleService, which addsStartingAsync,StartedAsync,StoppingAsyncandStoppedAsynchooks. On shutdown, when Kubernetes sends SIGTERM for example, the host cancelsstoppingTokenand waits up toHostOptions.ShutdownTimeout, 30 seconds by default, for every service to finish.Hosted services are registered as singletons, so I never inject a
DbContextdirectly. I injectIServiceScopeFactoryand create a scope per unit of work. The Worker Service template,dotnet new worker, is the same Generic Host without Kestrel, which I use when the background work should scale or fail separately from the API. The mistake I see is fire-and-forgetTask.Runin a controller instead of a proper hosted service with a queue."
| Type | What you implement | Use it for |
|---|---|---|
IHostedService |
StartAsync, StopAsync |
Short start-up/shutdown work, or full control |
BackgroundService |
ExecuteAsync(stoppingToken) |
Long-running loops: queue consumers, polling, timers |
IHostedLifecycleService (.NET 8+) |
Adds StartingAsync, StartedAsync, StoppingAsync, StoppedAsync |
Work that must run at a precise lifecycle stage, such as a warm-up |
| Worker Service template | Program.cs with Host.CreateApplicationBuilder and a Worker : BackgroundService |
A process with no HTTP server |
| Phase | What happens |
|---|---|
app.Run() |
Host starts |
| Start | Each hosted service's StartAsync in registration order; BackgroundService starts ExecuteAsync as a background task |
| Server | Kestrel starts listening; IHostApplicationLifetime.ApplicationStarted fires |
| Shutdown signal | SIGTERM, Ctrl+C or StopApplication(); ApplicationStopping fires |
| Stop | Kestrel stops accepting new requests and drains; StopAsync on services in reverse order cancels stoppingToken |
| Timeout | After ShutdownTimeout (30 s) the host stops waiting |
| In the web API | Separate Worker Service |
|---|---|
| Small, quick jobs (cache refresh, cleanup) | Heavy or long jobs (imports, PDF generation) |
| Same scaling as the API is fine | Needs its own scaling, for example on queue length with KEDA |
| A crash should take the API down anyway | Failures must not affect request handling |
In a [booking] API we had a BackgroundService that expired unpaid reservations every minute: [about 40 lines], using a PeriodicTimer and a scope per run. When we added PDF ticket generation, which used [up to 1 GB] of memory per batch, we moved it to a separate Worker Service consuming a queue, so a spike in PDF work could no longer slow down API requests.
Checks that the candidate knows how hosted services fit into the Generic Host lifecycle and can write a safe BackgroundService.
Green flags
IServiceScopeFactory for scoped servicesstoppingToken and knows ShutdownTimeoutExecuteAsync throwsRed flags
DbContext directly into a hosted serviceTask.Run for background workHost.StartAsync
├─ IHostedLifecycleService.StartingAsync (all)
├─ IHostedService.StartAsync (in registration order, or concurrently if HostOptions.ServicesStartConcurrently)
│ └─ BackgroundService.StartAsync: _executeTask = Task.Run(() => ExecuteAsync(stoppingToken)) (.NET 10)
├─ IHostedLifecycleService.StartedAsync (all)
└─ GenericWebHostService starts Kestrel → ApplicationStarted
SIGTERM
├─ ApplicationStopping
├─ Kestrel stops accepting, drains in-flight requests
├─ StopAsync in reverse order → BackgroundService cancels stoppingToken, awaits _executeTask (or the timeout)
└─ ApplicationStopped
In ASP.NET Core the web server itself is a hosted service registered last, which is why your services start before the server and stop after it.
Simplified:
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task? _executeTask;
private CancellationTokenSource? _stoppingCts;
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
_stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executeTask = Task.Run(() => ExecuteAsync(_stoppingCts.Token), _stoppingCts.Token); // .NET 10
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (_executeTask is null) return;
_stoppingCts!.Cancel();
await _executeTask.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
// ...
}
Before .NET 10, StartAsync called ExecuteAsync directly, so everything up to the first incomplete await ran synchronously on the start-up path.
HostOptions.ShutdownTimeout defaults to 30 seconds (it was 5 seconds before .NET 6). In Kubernetes, terminationGracePeriodSeconds also defaults to 30 seconds, and the pod is killed when it expires. If your timeout equals the grace period, there is no margin, so set the grace period a little longer than the host timeout.
If ExecuteAsync throws, the default BackgroundServiceExceptionBehavior.StopHost (since .NET 6) logs the error and stops the whole host. Ignore restores the old behaviour, where the service just stops silently and the app keeps running without it. Either way, a single exception ends your loop unless you catch inside it.
| Pattern | Notes |
|---|---|
PeriodicTimer in a loop |
Async, no overlapping runs, honours cancellation; the modern default |
Task.Delay loop |
Fine, but drifts by the run time |
System.Threading.Timer |
Callbacks can overlap; avoid for async work |
| Quartz.NET, Hangfire | Cron schedules, persistence, clustering, retries, dashboards |
dotnet new worker, add Thread.Sleep(10000) before the first await in ExecuteAsync, and compare start-up time on .NET 8 and .NET 10.IHostedLifecycleService and in IHostApplicationLifetime events, then press Ctrl+C and read the order.ExecuteAsync and watch the host stop; switch to BackgroundServiceExceptionBehavior.Ignore and see the difference.DbContext directly into a BackgroundService and read the scope-validation error in Development.docker stop, and confirm your loop exits within the timeout.A periodic BackgroundService that uses a scope per run, honours shutdown and survives transient failures.
// Program.cs (.NET 10). The same code works in a web API or in a Worker Service.
var builder = Host.CreateApplicationBuilder(args); // WebApplication.CreateBuilder(args) in an API
builder.Services.AddDbContext<BookingDb>();
builder.Services.AddHostedService<ExpireReservationsService>();
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));
builder.Build().Run();
public sealed class ExpireReservationsService(
IServiceScopeFactory scopeFactory,
ILogger<ExpireReservationsService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// PeriodicTimer: no overlapping runs, and WaitForNextTickAsync honours the stopping token.
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
do
{
try
{
// Hosted services are singletons: create a scope for scoped services like DbContext.
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<BookingDb>();
var expired = await db.ExpireUnpaidAsync(DateTimeOffset.UtcNow, stoppingToken);
logger.LogInformation("Expired {Count} unpaid reservations", expired);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break; // normal shutdown
}
catch (Exception ex)
{
// Without this catch, one transient SQL error would end the loop (and stop the host by default).
logger.LogError(ex, "Expiring reservations failed; will retry on the next tick");
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
}
public sealed class BookingDb : Microsoft.EntityFrameworkCore.DbContext
{
public Task<int> ExpireUnpaidAsync(DateTimeOffset now, CancellationToken ct) => Task.FromResult(0); // EF Core ExecuteUpdateAsync in real code
}
dotnet new worker -n Booking.Worker # Generic Host + BackgroundService, no Kestrel
DbContext or another scoped service into a hosted service's constructor. Why it is wrong: Hosted services are singletons, so the scoped service becomes a captive dependency shared for the app's lifetime (and scope validation throws in Development). Instead: Inject IServiceScopeFactory and create a scope per unit of work.StartAsync. Why it is wrong: Hosted services start before Kestrel listens, so readiness and the first requests wait. Instead: Keep StartAsync quick and do slow work in ExecuteAsync, or report readiness through a health check.stoppingToken. Why it is wrong: The loop keeps running after shutdown starts, and the host waits until ShutdownTimeout and then abandons it mid-work. Instead: Pass the token to every async call and check it in loops.ExecuteAsync. Why it is wrong: The loop ends; by default the whole host stops (StopHost), or with Ignore the work silently stops forever. Instead: Catch, log and continue inside the loop, and let only truly fatal errors escape.Task.Run in a controller for background work. Why it is wrong: No scope, no shutdown handling, lost exceptions, and work dies with the request's services. Instead: Queue the work (a Channel<T> or a message broker) and process it in a BackgroundService.System.Threading.Timer with an async callback. Why it is wrong: Callbacks can overlap and exceptions are lost. Instead: Use PeriodicTimer in ExecuteAsync.Hosted services make background work look trivially easy, which is exactly the danger. Ask three questions before writing one. What happens if the process dies mid-job? Is the work durable (a queue or a database row) or only in memory? What happens with three replicas? If the answers are "lost", "in memory" and "it runs three times", you need a queue, idempotency or a scheduler, not just a loop.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
BackgroundService in the API |
Light, idempotent, per-instance work (cache refresh, local cleanup) | Almost none | Heavy CPU or memory work, exactly-once jobs |
| Separate Worker Service | Queue consumers, heavy jobs, separate scaling (KEDA on queue length) | Another deployable | Tiny jobs that don't justify it |
| Quartz.NET or Hangfire | Cron schedules, persistence, retries, one run per cluster, a dashboard for support staff | A library and a job store (SQL Server, Redis) | A simple interval loop on one instance |
| Azure Functions or Container Apps jobs | Event-driven or scheduled jobs with scale to zero, e.g. a nightly export | Platform lock-in, cold starts, execution time limits on some plans | Long-running stateful loops, sub-second latency |
IHostedService vs IHostedLifecycleService |
Use when |
|---|---|
IHostedService |
You only need start and stop |
IHostedLifecycleService |
Something must happen before every service starts (StartingAsync), after all have started (StartedAsync, e.g. mark ready), or before stop begins (StoppingAsync, e.g. stop pulling from a queue) |
In .NET 10 the start-up blocking trap is gone, but the other traps remain: the singleton lifetime, exception behaviour and shutdown timing. Also note that a synchronous, CPU-bound or blocking loop still holds a ThreadPool thread for its whole life, so keep loops truly async.
Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
A foreground thread keeps the process alive: the runtime waits for every foreground thread to finish before the process exits. A background thread does not: when the last foreground thread ends, background threads are stopped immediately and their finally blocks do not run. New Thread objects are foreground by default; ThreadPool threads (and therefore Task.Run work) are always background. So background work needs an explicit graceful shutdown, or it is cut off mid-operation.
Last updated 23 Nov 2026.