Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 182 ยท Dependency Injection and Hosting

The Generic Host and BackgroundService

Learn the .NET Generic Host - Host.CreateApplicationBuilder, hosted services, BackgroundService, cancellation, graceful shutdown, lifetime events, scoped services in workers and worker patterns.

Many programs are not "run once and exit". A web server waits for requests. A worker reads messages from a queue. A service refreshes a cache every minute. These programs share the same needs: build a set of services, read configuration, set up logging, start some long-running work, and shut down cleanly when the operating system says "stop".

.NET packages all of that into the Generic Host. You create it with Host.CreateApplicationBuilder(), register your services, build it, and run it. ASP.NET Core is built on top of it, so what you learn here applies to every web app too. The long-running work lives in hosted services, and the most convenient way to write one is to derive from BackgroundService.

By the end of this lesson you will know what the host sets up for you, how to write a worker that stops politely, how to react to lifetime events, how to use scoped services inside a singleton worker, and which patterns real worker services use.

The host lives in Microsoft.Extensions.Hosting, included in our runner. In a project of your own, a console app gets it from the Microsoft.Extensions.Hosting NuGet package, and a project using Sdk="Microsoft.NET.Sdk.Worker" (the Worker Service template) already references it.

What the host gives you

Host.CreateApplicationBuilder(args) returns a HostApplicationBuilder that is already configured with sensible defaults:

  • Dependency injection: builder.Services is the service collection from Dependency Injection.
  • Configuration: builder.Configuration merges appsettings.json, environment-specific files, environment variables and command-line arguments (see Configuration and Options).
  • Logging: builder.Logging, with console and debug providers on by default (Logging).
  • Environment: builder.Environment tells you the app name and whether it is Development or Production.
  • Lifetime management: the host listens for Ctrl+C and SIGTERM and shuts down gracefully.

You then call builder.Build(), which gives an IHost, and run it. Let's look at that in the smallest form and see what the container knows:

C# Build a host and inspect it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The environment defaults to Production unless the DOTNET_ENVIRONMENT variable says otherwise (ASP.NET Core also reads ASPNETCORE_ENVIRONMENT). We never called Run, so nothing started: building a host only wires things up. Run() is what starts it.

Host.CreateDefaultBuilder(args) is the older style (it uses ConfigureServices callbacks). Host.CreateApplicationBuilder is the modern form, the same shape as WebApplication.CreateBuilder, and the one to use in new code.

Hosted services

A hosted service is a class that implements IHostedService:

C#
public interface IHostedService
{
    Task StartAsync(CancellationToken cancellationToken);
    Task StopAsync(CancellationToken cancellationToken);
}

When the host starts, it calls StartAsync on every registered hosted service in registration order, and waits for each to finish before starting the next. When the host stops, it calls StopAsync in reverse order. StartAsync must return quickly: it is for starting work, not for doing it. Registration is one line:

C#
builder.Services.AddHostedService<MyService>();

The next example registers two plain IHostedService classes so you can watch the order. StartAsync and StopAsync are called by StartAsync() and StopAsync() on the host. (Run is just "start, wait for shutdown, stop".)

C# Start in order, stop in reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The cache was started second, so it stops first. That mirrors a stack: the thing that depends on others goes up last and comes down first.

BackgroundService: a worker loop

Implementing both methods by hand is tedious for the common case "run this loop until the app stops". BackgroundService is an abstract base class that does the bookkeeping. You override one method:

C#
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

BackgroundService calls ExecuteAsync when the host starts and stores the returned task. It does not wait for that task before starting the next service, so your method can run for hours. When the host stops, it signals stoppingToken and then awaits your task so you can finish.

Your loop must therefore watch the token. Two rules:

  1. Pass stoppingToken to every awaited call that accepts one (Task.Delay, HttpClient, channel reads).
  2. Check stoppingToken.IsCancellationRequested in loop conditions.
C# A worker that stops when asked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The worker prints a tick immediately and then roughly every 100 ms; after about 280 ms the host asks it to stop, Task.Delay throws OperationCanceledException, and the loop ends. The exact number of ticks depends on timing, so do not rely on it in real tests; here we waited long enough that three ticks are typical.

BackgroundService already ignores an OperationCanceledException thrown from ExecuteAsync that is caused by stoppingToken, so catching it is optional. We catch it here only to run a line of cleanup afterwards. A try/finally is the usual alternative.

What if ExecuteAsync throws?

Since .NET 6, an unhandled exception in ExecuteAsync stops the whole host by default (BackgroundServiceExceptionBehavior.StopHost). That is deliberate: a worker that silently died would leave an application that looks healthy but does nothing. You can change it with HostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore, but a better approach is to catch exceptions inside the loop, log them and carry on:

C#
while (!stoppingToken.IsCancellationRequested)
{
    try
    {
        await DoOneUnitOfWorkAsync(stoppingToken);
    }
    catch (Exception ex) when (ex is not OperationCanceledException)
    {
        logger.LogError(ex, "Work failed, will retry");
        await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);   // back off
    }
}

Catching around the body keeps one bad item from killing the worker, and the when filter (see Exception Filters) lets cancellation pass through.

Blocking before the first await

In older .NET versions, ExecuteAsync ran synchronously until its first real await, so long synchronous work at the top (reading a big file, a CPU loop) delayed host startup and the next service could not start. Since .NET 10 the host no longer waits for that synchronous part (we measured it on the runner: a 400 ms Thread.Sleep before the first await did not delay StartAsync). Still, blocking a thread-pool thread is wasteful and the habit breaks on older runtimes, so put await Task.Yield() first or keep the work asynchronous. Never use .Result or .Wait() here (Async Pitfalls).

Periodic work with PeriodicTimer

For "do this every N seconds", PeriodicTimer is the neat tool. It does not drift the way await Task.Delay after the work does, and it never lets ticks pile up while the work is still running.

C# PeriodicTimer in a worker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Here the main program waits for the worker's progress instead of guessing with a fixed delay. When you must observe a background worker (in a demo or a test), wait for a signal, such as a counter, a TaskCompletionSource or a Channel, never for "long enough". Notice that RefreshWorker takes the shared Counter through its primary constructor; hosted services are created by the container and can use dependency injection like any other service.

Lifetime events and graceful shutdown

IHostApplicationLifetime is a service with three cancellation tokens and one method:

Member Meaning
ApplicationStarted The host has started and all hosted services have run StartAsync.
ApplicationStopping Shutdown has begun (Ctrl+C, SIGTERM or StopApplication). Finish or stop accepting work.
ApplicationStopped Shutdown is complete.
StopApplication() Ask the host to stop, from inside your code.

You react by registering callbacks on the tokens. A common use is a run-once program that exits when its job is done:

C# Lifetime events and StopApplication

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sequence is: started, the job's own lines, stopping, stopped, and only then does RunAsync return. If you register the callbacks in the program itself, as above, you see how the pieces interleave.

How shutdown really works

When the host is asked to stop:

  1. ApplicationStopping fires, so code can stop taking new work.
  2. StopAsync is called on hosted services in reverse order. For a BackgroundService this cancels stoppingToken and awaits your ExecuteAsync.
  3. ApplicationStopped fires.

The whole process is limited by HostOptions.ShutdownTimeout (30 seconds in .NET 8 and later; it was 5 seconds before). If a worker has not finished in time, the host stops waiting and the process exits, possibly mid-work. So: finish or hand back in-flight work quickly, and write the work so that stopping half-way is safe (idempotent steps, transactions, retries).

Let's give one worker a slow shutdown and see how the options behave:

C# Graceful shutdown and the shutdown timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The worker gets its 200 ms of cleanup because that is well inside the 2-second shutdown timeout we configured. Note the cleanup delay deliberately does not use stoppingToken: that token is already cancelled, so passing it would abort the cleanup immediately.

Scoped services in a singleton worker

A hosted service is registered as a singleton: one instance for the life of the app. That creates a well-known problem. If your worker needs a scoped service (a database context, a per-unit-of-work object), you cannot inject it into the constructor. With scope validation on (the default in Development), the container throws:

TEXT
Cannot consume scoped service 'Repository' from singleton 'ReportWorker'.

The solution is to take IServiceScopeFactory and create a scope per unit of work:

C# A new scope for each round of work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each round gets a fresh Repository (ids 1, 2, 3), and the scope is disposed at the end of the round, which releases anything scoped and disposable. This is exactly what ASP.NET Core does for each web request.

Worker patterns

1. Queue consumer. The worker reads items from a Channel<T> that other parts of the app write to. This turns "do it later, in the background" into a safe pattern, for example sending e-mails without delaying a request.

C# A background queue worker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Here the worker reads without stoppingToken on purpose, so that StopAsync waits until it has drained the closed channel. In a long-running service you would pass the token and decide how to treat leftover items (persist them, or drain with a deadline).

2. Scheduled job. PeriodicTimer (above) for fixed intervals. For cron-like schedules ("every day at 02:00") people use a library such as Quartz.NET or Hangfire.

3. Pollers and watchers. Check a folder, a database table or an external API, process what is new, repeat. Always add a delay or timer so the loop does not spin at 100 % CPU.

4. Startup tasks. For one-off initialisation (migrations, warming a cache) a plain IHostedService.StartAsync is enough: the host waits for it, and the app only reports started when it is done. For work that must not block startup, use BackgroundService.

5. Several workers. Register more hosted services, or use AddHostedService for each. They run independently and share nothing except what you inject.

Things to remember

  • Never async void. Returning void from ExecuteAsync would hide exceptions.
  • Never block the thread pool in a worker with Thread.Sleep or .Wait(). Use await.
  • BackgroundService instances are singletons. Fields are shared; protect them with locks or interlocked operations, as the counter above does.
  • Dispose of what you create. Use using for timers and scopes.
  • Observe the token everywhere. A worker that ignores stoppingToken slows down every deployment, because the host waits until its timeout and then kills the process.
  • Run vs Start. host.Run() / RunAsync() blocks until shutdown; it is what Program.cs of a real service calls. StartAsync / StopAsync give you manual control, which is handy in tests and demos like these.

In a project of your own, the worker service template creates exactly this shape:

C#
// Program.cs (read-only: created by "dotnet new worker")
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();

var host = builder.Build();
host.Run();

Running it as a Windows Service or a Linux systemd unit is one extra call (AddWindowsService() / AddSystemd() from small NuGet packages), and a container orchestrator such as Kubernetes simply sends SIGTERM, which the host turns into the graceful shutdown you saw above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does the host stop its hosted services?

    StartAsync is called in registration order and StopAsync in reverse, so services that were started last (and may depend on earlier ones) stop first.
  2. 2. What is BackgroundService.ExecuteAsync for?

    BackgroundService calls ExecuteAsync at startup and keeps the task. It does not wait for it to complete, so the method may run for the whole life of the app. On shutdown the host cancels the stopping token and awaits the task.
  3. 3. Why can't a hosted service take a scoped service in its constructor?

    A singleton lives as long as the app, so a scoped dependency would never be released. Inject IServiceScopeFactory and create a scope for each unit of work.
  4. 4. A worker loop calls await Task.Delay(1000) without a token. What is the main drawback?

    Without stoppingToken the delay always completes. Repeated across slow operations this makes shutdown slow, and when the shutdown timeout is exceeded the process is ended abruptly.
  5. 5. What does IHostApplicationLifetime.StopApplication() do?

    StopApplication triggers the normal shutdown sequence: ApplicationStopping, StopAsync on the hosted services in reverse order, then ApplicationStopped.

Summary

  • The Generic Host bundles dependency injection, configuration, logging and lifetime management. Create it with Host.CreateApplicationBuilder(), register services, Build() and Run().
  • Hosted services (IHostedService) start in registration order and stop in reverse. BackgroundService gives you ExecuteAsync(stoppingToken) for long-running loops.
  • Always pass and observe the stopping token; catch exceptions inside the loop so one failure does not stop the host.
  • PeriodicTimer is the right tool for fixed-interval work; channels are the right tool for background queues.
  • IHostApplicationLifetime exposes started, stopping and stopped events and StopApplication(); the shutdown timeout is 30 seconds by default.
  • Workers are singletons: use IServiceScopeFactory to get scoped services per unit of work.

Next: Caching and HttpClientFactory