Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 52 ยท Advanced Topics

Background Services and Hosted Services

Run work outside requests with IHostedService and BackgroundService: timers, Channel<T> queues, scoped services in singletons and graceful shutdown.

Not everything should happen inside a request. Sending an email, resizing an image, refreshing a cache every minute or draining a queue of webhook calls should not make a user wait, and some of that work has no request at all that triggers it. ASP.NET Core runs such work inside the same process as your web app with hosted services: classes that the host starts when the application starts and stops when it shuts down.

In this lesson you will learn the two building blocks (IHostedService and BackgroundService), how to hand work from endpoints to a worker with Channel<T>, how to use scoped services such as a database context from a long-lived worker, and how to shut down gracefully without losing queued work. If you need a refresher on async code, see the C# async lessons; the host and builder are covered in The Host and the Builder.

IHostedService and BackgroundService

IHostedService is a two-method contract:

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

The host calls StartAsync on every registered hosted service, in registration order, when the app starts, and StopAsync in reverse order when it stops. StartAsync must return quickly: while it runs, the application is not yet ready to serve requests. So a service that wants to keep working has to start its work and return.

BackgroundService is a base class that does exactly that for you. You override one method, ExecuteAsync(CancellationToken stoppingToken), and the base class starts it as a long-running task from StartAsync. When the host stops, the base class signals stoppingToken and waits for your method to finish.

sequenceDiagram
    participant H as Host
    participant G as Greeter (IHostedService)
    participant T as Ticker (BackgroundService)
    H->>G: StartAsync
    H->>T: StartAsync (starts ExecuteAsync)
    T-->>T: ExecuteAsync loops in the background
    Note over H: app is running, serving requests
    H->>T: StopAsync (cancels stoppingToken, waits)
    T-->>T: loop sees cancellation and returns
    H->>G: StopAsync

Start in registration order, stop in reverse order; a BackgroundService keeps working between the two calls.

You register hosted services with AddHostedService<T>(). Hosted services live as singletons for the life of the application, which matters in the third section. Here is the lifecycle in action, using the plain generic host (no web server needed; a web app behaves the same).

C# The lifecycle of hosted services

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.

Read the output from top to bottom. Services start in the order they were registered, ExecuteAsync begins running at once, and during shutdown the last registered service stops first. That reverse order is deliberate: a service that depends on an earlier one (a worker that uses a queue created by another service) is shut down before the thing it depends on.

PeriodicTimer is the modern way to write "do something every N seconds" in a worker. Unlike Task.Delay in a loop it does not drift by the time your work takes, and WaitForNextTickAsync(stoppingToken) returns promptly when the host stops.

Exceptions matter. Since .NET 6, an unhandled exception inside ExecuteAsync stops the whole host by default (BackgroundServiceExceptionBehavior.StopHost), and your website goes down with it. Catch exceptions around each unit of work, log them, and keep the loop alive. Let only OperationCanceledException from stoppingToken end the loop quietly.

Queues with Channel<T>

The most useful background pattern in a web app is a work queue: the endpoint accepts a request, writes a job into a queue and returns 202 Accepted immediately, and a worker takes jobs out and processes them. In .NET the right in-process queue is System.Threading.Channels.Channel<T>: a thread-safe, async-friendly producer/consumer pipe.

flowchart LR
    R1["POST /jobs"] -->|"Writer.TryWrite"| C[("Channel&lt;Job&gt;<br/>bounded, capacity 3")]
    R2["POST /jobs"] -->|"Writer.TryWrite"| C
    C -->|"Reader.ReadAllAsync"| W["Worker<br/>(BackgroundService)"]
    W --> S["Results store"]
    R3["GET /jobs/id"] --> S

Endpoints write, the worker reads; the channel decouples the speed of requests from the speed of processing.

A channel can be unbounded (never blocks writers, but memory grows without limit if the worker is slower than the producers) or bounded (a fixed capacity). Prefer bounded for anything user-facing: when the queue is full, Writer.TryWrite returns false and you can answer 503 Service Unavailable with a Retry-After header, which is much better than running out of memory. This is called backpressure.

The example holds the worker back with a gate so the queue fills up predictably: capacity 3, five submissions, so exactly two are refused. Then it opens the gate and watches the jobs complete in order.

C# A bounded work queue with backpressure

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.

Three details to copy into real code. The endpoint only enqueues and returns at once, using 202 Accepted and a Location header so the client knows where to check. The worker wraps each job in its own try/catch so a failing job is recorded without ending the loop. And ReadAllAsync(stoppingToken) gives a clean await foreach that ends when the token is cancelled.

An in-process channel has one important limit: if the process dies, queued jobs die with it. That is fine for emails you can regenerate, thumbnails and cache warm-ups. For work that must not be lost (payments, orders), persist the job first (a database "outbox" table) or use a real message broker, and let the in-memory channel only be a performance optimization.

Scoped services inside a singleton

Hosted services are singletons, but many useful services (a database context, a unit of work) are scoped: they are meant to live for one request. A singleton cannot take a scoped service in its constructor. That would be a captive dependency: the scoped object would live as long as the singleton, long after it should have been disposed, shared across threads and holding stale data. With scope validation on (the default in the Development environment) the container refuses to build such a graph and tells you so.

The fix is to create your own scope for each unit of work, with IServiceScopeFactory:

C#
using IServiceScope scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// use db for this one job, then the scope is disposed

This mimics what ASP.NET Core does per request: one scope for the job, and everything scoped inside is created once, shared within the job and disposed at the end. The example first shows the container rejecting the captive dependency, then the correct pattern.

C# Creating a scope per job

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.

Every job got a fresh unit of work (#1, #2, #3), it was shared inside its own scope and it was disposed when the scope ended. The same pattern works for DbContext, which must never be shared between threads or jobs (Dependency Injection in ASP.NET Core explains lifetimes, and Entity Framework Core Overview the context).

Graceful shutdown

Servers restart all the time: every deployment, every scale-down, every crash recovery. What should happen to work in flight? ASP.NET Core stops in this order: the host raises ApplicationStopping, the web server stops accepting new connections and finishes current requests, then hosted services are stopped (in reverse order), each waiting for its ExecuteAsync to return. The total time allowed is HostOptions.ShutdownTimeout (30 seconds by default in current versions); after that the host stops waiting and the process exits, abandoning whatever is still running.

You have two honest choices for queued work:

  • Abandon on stop. Pass stoppingToken to everything and exit at once. Simple, and fine when the work can be rebuilt.
  • Drain on stop. Stop accepting new items, finish what is already queued, then exit. For that, complete the channel's writer in an overridden StopAsync and let the reader loop run until the channel is empty (do not pass stoppingToken to ReadAllAsync).

If draining may take longer than the timeout, raise ShutdownTimeout (and the orchestrator's own grace period, such as Kubernetes' terminationGracePeriodSeconds), or persist the leftovers so the next instance picks them up.

C# Abandon versus drain on shutdown

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.

In the first scenario the stop signal arrives while the first mail is being sent. The worker finishes that one, sees the signal and abandons the other three. In the second it ignores the signal, finishes all four and only then exits, and StopAsync returns after that. Both versions close the writer first, so mail submitted after stopping is refused rather than silently queued for nobody.

Other ways to run background work

  • IHostApplicationLifetime lets any service react to ApplicationStarted, ApplicationStopping and ApplicationStopped, or request shutdown with StopApplication().
  • Timers inside a hosted service are fine for in-process periodic work. For schedules with cron expressions, persistence or running on exactly one server of many, use a scheduler library such as Quartz.NET or Hangfire.
  • A separate worker process. The Worker Service template is the same hosting model without the web server. Move heavy or critical jobs there when they should scale and deploy independently from the web app.
  • Do not use Task.Run fire-and-forget in endpoints. The task has no owner: it is not awaited, not stopped at shutdown, and an exception in it can vanish. A channel plus a hosted service is the safe version of the same idea.

You will see real usage of this chapter's pieces in later lessons: Calling Other Services: HttpClient and Resilience and the real-time lessons both rely on workers and channels.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does the host call StopAsync on hosted services A, B and C that were registered in that order?

    Services start in registration order and stop in reverse, so a service that depends on an earlier one stops before the thing it depends on.
  2. 2. An unhandled exception is thrown from ExecuteAsync of a BackgroundService. What happens by default in current .NET versions?

    BackgroundServiceExceptionBehavior.StopHost is the default. Catch and log exceptions around each unit of work so one failure does not stop the application.
  3. 3. Why is a bounded Channel<T> usually better than an unbounded one for a queue fed by user requests?

    An unbounded queue grows without limit if producers outrun the worker. A bounded one applies backpressure: TryWrite returns false and the endpoint can reject the request.
  4. 4. A hosted service needs a scoped DbContext for each job. What is the right approach?

    Constructor injection would capture one scoped instance for the whole application lifetime. A scope per job gives a fresh instance that is disposed afterwards.
  5. 5. Which pattern lets a worker finish already-queued items on shutdown?

    Completing the writer rejects new items and ends the reader loop only after the remaining items have been read.

Summary

  • Hosted services start in registration order and stop in reverse; BackgroundService gives you a long-running ExecuteAsync with a stopping token.
  • Catch exceptions inside the loop; an unhandled one stops the host by default.
  • Use a bounded Channel<T> as an in-process queue: endpoints enqueue and return 202, workers dequeue, and a full queue means backpressure (503).
  • In-memory queues are lost on a crash; persist work that must not be lost.
  • Hosted services are singletons, so create a scope per job with IServiceScopeFactory to use scoped services.
  • Choose abandon or drain on shutdown, and respect ShutdownTimeout.

Next: Calling Other Services: HttpClient and Resilience