Hosted services and lifetime
Hosted services and lifetime
A hosted service is a component whose start and stop lifecycle belongs to the .NET host. A background worker processes work independently of a request; it must own the lifetime of each work unit and cooperate with shutdown.
A generic host wires configuration, logging, dependency injection and application lifetime together. IHostedService exposes StartAsync and StopAsync; BackgroundService adds ExecuteAsync for the lifetime of the worker. In .NET 10 the entire ExecuteAsync runs as a background task; do not rely on its synchronous prefix as a startup barrier. Use explicit startup or readiness coordination for prerequisites. AddHostedService registers a singleton hosted service. A scoped database context cannot be injected into that singleton and kept across jobs: inject IServiceScopeFactory, open a fresh scope per job, await the work, and dispose the scope. A worker may run on every replica, so a timer alone does not ensure only one job globally. A PeriodicTimer has one consumer and coalesces missed ticks; it does not persist scheduling. Cancellation is cooperative, not a guarantee of termination. Set a shutdown budget, stop accepting work, finish or relinquish in-flight work, and observe failures. A crash may bypass graceful cleanup. Measure queue age, processing duration, failures and shutdown time. Avoid async void, unbounded Task.Run and holding scoped objects after their scope closes.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models and isolated local integration fixtures are explicitly distinguished.
Give each job its own scope
Use the real DI container. Two jobs should receive distinct scoped objects; resolving twice within one scope should return the same object.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework.
using System;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddScoped<JobSession>();using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true });var factory = provider.GetRequiredService<IServiceScopeFactory>();JobSession? first = null;for (int job = 1; job <= 2; job++) { using var scope = factory.CreateScope(); var session = scope.ServiceProvider.GetRequiredService<JobSession>(); var again = scope.ServiceProvider.GetRequiredService<JobSession>(); Console.WriteLine($"job {job}: same scope={ReferenceEquals(session, again)}; reused prior={ReferenceEquals(first, session)}"); first = session;}sealed class JobSession : IDisposable { public void Dispose() => Console.WriteLine("scope disposed");}Expected result (not executed):
job 1: same scope=True; reused prior=Falsescope disposedjob 2: same scope=True; reused prior=Falsescope disposedThe saved reference is used only for identity comparison; never call a disposed scoped service. An async-disposable dependency needs CreateAsyncScope and await using.
Run a finite hosted worker
The host owns the worker. A completion signal makes the fixture finite without timing-based assertions; a five-second guard bounds waiting.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework.
using System;using System.Threading;using System.Threading.Tasks;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;var builder = Host.CreateApplicationBuilder();builder.Logging.ClearProviders();builder.Services.AddScoped<Job>();builder.Services.AddSingleton<Completion>();builder.Services.AddHostedService<Worker>();using var host = builder.Build();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(5));await host.StartAsync(deadline.Token);try { await host.Services.GetRequiredService<Completion>().Done.Task.WaitAsync(deadline.Token); }finally { using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await host.StopAsync(stop.Token); }Console.WriteLine("host stopped");sealed class Completion { public TaskCompletionSource Done { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); }sealed class Job { public Task RunAsync(int n, CancellationToken token) { token.ThrowIfCancellationRequested(); Console.WriteLine($"processed {n}"); return Task.CompletedTask; } }sealed class Worker(IServiceScopeFactory scopes, Completion completion) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { for (int n = 1; n <= 2; n++) { await using var scope = scopes.CreateAsyncScope(); await scope.ServiceProvider.GetRequiredService<Job>().RunAsync(n, stoppingToken); } completion.Done.TrySetResult(); } catch (Exception e) { completion.Done.TrySetException(e); throw; } }}Expected result (not executed):
processed 1processed 2host stoppedA scope ends before completion is signaled. In a long-lived worker use a bounded queue and stop token, not a fixed job list. A deadline expiring fails this fixture; it is not a measured performance result.
Cancel a pending periodic wait
Cancel before waiting. A long period avoids relying on the clock for a successful tick.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;using System.Threading;using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));using var stop = new CancellationTokenSource();stop.Cancel();try { await timer.WaitForNextTickAsync(stop.Token); }catch (OperationCanceledException) when (stop.IsCancellationRequested) { Console.WriteLine("shutdown requested"); }Console.WriteLine("leaving worker loop");Expected result (not executed):
shutdown requestedleaving worker loopCancellation stops this wait. The using declaration disposes the timer at scope exit. A real periodic loop awaits each tick and finishes or cancels the current operation before disposal.
Apply the concept
A worker processes three inventory jobs with a scoped repository. Sketch the scope boundaries and a shutdown while job 2 is running.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Hosted services and lifetime — knowledge check
Apply the lesson concepts to the following scenarios.
Why create a scope per work unit?
What changed in .NET 10 BackgroundService startup?
What happens to missed PeriodicTimer ticks?
What does shutdown cancellation guarantee?
Two replicas register the same hosted service. How many workers may run?