skip to content

Off-Request Processing

Running work inside the web process but outside any request: BackgroundService loops and in-process queues built on channels. Interviewers probe what happens to that work on shutdown.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

11

In ASP.NET Core, what is the difference between implementing IHostedService directly and deriving from BackgroundService, and how is either one registered?

level: juniorimportance: must knowfreq 62%

answer

  1. two start/stop methods vs one loop
  2. StartAsync blocks the next service
  3. ExecuteAsync(CancellationToken stoppingToken)
  4. AddHostedService<T>() registers a singleton
  5. TryAddEnumerable: second call ignored

basics

~10 s

IHostedService gives you StartAsync and StopAsync and nothing else; BackgroundService implements both and asks only for ExecuteAsync(stoppingToken), the long-running loop. Either is registered with builder.Services.AddHostedService<T>(), which adds a singleton.

solid answer

~40 s

`IHostedService` is the raw contract: the host calls `StartAsync` when the app starts and `StopAsync` when it shuts down, and you own every thread, timer and cancellation in between. `BackgroundService` is an abstract base class that implements both for you: its `StartAsync` starts your `ExecuteAsync(CancellationToken stoppingToken)` as a task and returns at once, and its `StopAsync` cancels `stoppingToken` and waits for that task. So a loop goes in a `BackgroundService`, while short start-up or shut-down work fits a plain `IHostedService`. Both are registered with `builder.Services.AddHostedService<T>()`, which adds the type as a **singleton** `IHostedService`. Calling it twice for the same type still registers one instance.

code

csharp · 17 lines
csharp
public sealed class MeterSyncService(ILogger<MeterSyncService> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            logger.LogInformation("Pulling meter readings");
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<MeterSyncService>();
var app = builder.Build();
app.Run();

go deeper

for a junior

Recall the two shapes: IHostedService with StartAsync and StopAsync, BackgroundService with one ExecuteAsync loop, and AddHostedService<T>() to register either.

for a middle

Explain what BackgroundService's StartAsync and StopAsync do for you, why the instance is a singleton, and why the host's sequential start makes StartAsync the wrong place for a loop.

for a senior

Show the consequences in production: registration order against the web server, duplicate registrations collapsing, and that every process registering the service runs its own copy.

for a principal

Frame when in-process hosted services are the right home for background work at all, versus a separate worker deployment or a durable scheduler that survives restarts.

## Two contracts for work that lives as long as the app An ASP.NET Core app runs on the .NET Generic Host. Besides the web server, the host can run **hosted services**: objects it starts when the app starts and stops when the app shuts down. They are the framework's built-in place for work that is not tied to one HTTP request: a loop that polls meter readings, a cache warm-up, a consumer that reads a queue. There are two ways to write one: | | `IHostedService` | `BackgroundService` | |---|---|---| | Kind | interface in `Microsoft.Extensions.Hosting` | abstract class implementing `IHostedService` and `IDisposable` | | You write | `StartAsync(CancellationToken)` and `StopAsync(CancellationToken)` | `ExecuteAsync(CancellationToken stoppingToken)` | | Start-up | the host awaits your `StartAsync` before starting the next service | `StartAsync` starts `ExecuteAsync` as a task and returns a completed task | | Shut-down | you stop your own timers or tasks | `StopAsync` cancels `stoppingToken`, then waits for `ExecuteAsync` | | Fits | short start and stop work, or a timer you manage yourself | a loop that runs for the life of the app | ## What BackgroundService does for you `BackgroundService` is small, and knowing its body is what interviewers check: - `StartAsync` creates a `CancellationTokenSource` linked to the start-up token and, in .NET 10, runs **all** of `ExecuteAsync` through `Task.Run`, storing the task in the public `ExecuteTask` property. - It returns `Task.CompletedTask` at once, so a never-ending loop does not hold up start-up. - `StopAsync` cancels the token your loop received as `stoppingToken` and then waits for `ExecuteTask` to finish, bounded by the host's shutdown token. - `Dispose` cancels the same token source. - The host watches `ExecuteTask`: if it faults, the host logs the exception and, by default, stops the application. Only `ExecuteAsync` is abstract; `StartAsync`, `StopAsync` and `Dispose` are virtual, so you override them only to add behaviour, and you call the base implementation when you do. ## Registering: AddHostedService `AddHostedService<THostedService>()` (namespace `Microsoft.Extensions.DependencyInjection`) adds a `ServiceDescriptor.Singleton<IHostedService, THostedService>` through `TryAddEnumerable`. Three consequences follow: 1. **One instance per process.** A hosted service is a singleton, so it cannot take a scoped service such as a `DbContext` in its constructor; it creates a scope per unit of work instead. 2. **Duplicate calls collapse.** `TryAddEnumerable` skips a second registration of the same implementation type, so calling `AddHostedService<MeterSyncService>()` twice still runs one loop. 3. **Order matters.** The host resolves `IEnumerable<IHostedService>` and starts the services in registration order, one after another by default. `WebApplicationBuilder.Build()` appends the web server's own hosted service after yours, so your `StartAsync` methods finish before Kestrel starts listening. An overload takes a factory, `AddHostedService<T>(Func<IServiceProvider, T>)`, for a service that needs construction logic. ## Choosing between them - Pick **`BackgroundService`** for anything that loops: polling, draining a queue, a periodic sweep. You write one method and get cancellation and shutdown waiting for free. - Pick **plain `IHostedService`** when the work is a step at start or stop: warm a cache before the server listens, flush a buffer at shutdown. Because the host awaits `StartAsync`, a long-running loop placed there would keep every later service, and the server itself, from starting. - Hosted services start when the host starts, not on the first request, and they run in every process that registers them. ## Traps interviewers probe - **Overriding `StartAsync` without calling `base.StartAsync`.** `ExecuteAsync` is then never started, `ExecuteTask` stays `null`, and the host has nothing to watch; the service silently does nothing. - **Overriding `StopAsync` without calling `base.StopAsync`.** The loop is never told to stop, so shutdown waits for the timeout. - **Injecting the hosted service elsewhere.** `AddHostedService<T>()` registers it only as `IHostedService`, so asking the container for `T` fails. Register `T` as a singleton and forward it with the factory overload, `AddHostedService(sp => sp.GetRequiredService<T>())`, so the host and the consumers share one instance. - **Expecting one copy per deployment.** Each process that runs the app starts its own instance. ## A worked example In a water-utility billing app, a service that pulls meter readings from the field system every few minutes is a `BackgroundService`: a `while` loop in `ExecuteAsync` that awaits a delay with `stoppingToken`. A service that loads tariff tables into memory before the first bill is calculated is an `IHostedService` whose `StartAsync` does the load and whose `StopAsync` returns `Task.CompletedTask`.

  • Why does a long loop placed in IHostedService.StartAsync delay the whole app?
    The host awaits each hosted service's `StartAsync` in turn, and by default (`HostOptions.ServicesStartConcurrently` is false) it starts them one at a time. In a `WebApplication` the web server's hosted service is registered after yours, so a `StartAsync` that never completes means Kestrel never starts listening. Long-running work belongs in `BackgroundService.ExecuteAsync`, which the base class starts as a task.
  • Can a BackgroundService take a scoped service such as a DbContext in its constructor?
    No. `AddHostedService` registers it as a singleton, so a scoped dependency would be captured for the life of the app, and with scope validation on in Development the container refuses to resolve it. The service injects `IServiceScopeFactory` instead and creates a scope for each unit of work.

  • AddHostedService registers the service as scoped, one instance per request
  • Deriving from BackgroundService means overriding StartAsync and StopAsync
  • A hosted service also needs AddSingleton<T>() or the host never starts it
  • Put the endless loop in IHostedService.StartAsync so it starts early
  • A hosted service starts lazily when the first HTTP request arrives
open as a page

In an ASP.NET Core BackgroundService, how should ExecuteAsync use its stoppingToken, and what happens at shutdown when the loop ignores it?

level: middleimportance: must knowfreq 55%

basics

~20 s

stoppingToken is cancelled when the host calls StopAsync, so the loop checks it and passes it to every awaited call. A loop that ignores it keeps running until the shutdown timeout, then is cut off mid-work when the process exits.

open as a page

For an ASP.NET Core work queue on System.Threading.Channels, when do you choose CreateBounded over CreateUnbounded, and what does BoundedChannelFullMode control?

level: middleimportance: must knowfreq 52%

basics

~20 s

Choose CreateBounded for any queue fed by HTTP traffic, because an unbounded channel grows until memory runs out. BoundedChannelFullMode decides what a write does when the channel is full: Wait (the default) waits for room; DropNewest, DropOldest and DropWrite discard an item.

open as a page

In ASP.NET Core, how do you hand work from an endpoint to a background consumer using a System.Threading.Channels Channel<T>?

level: juniorimportance: should knowfreq 45%

basics

~10 s

Register one Channel<T> as a singleton. The endpoint writes a job with channel.Writer.WriteAsync and returns 202 Accepted; a BackgroundService reads jobs one by one with await foreach over channel.Reader.ReadAllAsync(stoppingToken).

open as a page

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%

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.

open as a page

For a recurring job in an ASP.NET Core BackgroundService, why prefer PeriodicTimer over Task.Delay or System.Threading.Timer, and how does WaitForNextTickAsync behave?

level: middleimportance: should knowfreq 42%

basics

~20 s

PeriodicTimer keeps a fixed cadence without overlapping runs: the loop awaits WaitForNextTickAsync(stoppingToken), which returns true per tick, false once the timer is disposed, and throws when the token is cancelled. Missed ticks coalesce into one.

open as a page

How do you consume a System.Threading.Channels queue with limited concurrency in an ASP.NET Core BackgroundService, and which ChannelOptions settings matter?

level: middleimportance: should knowfreq 28%

basics

~20 s

Start a fixed number of reader loops over the same ChannelReader and await them together; each item goes to exactly one reader. Keep SingleReader false with several readers and AllowSynchronousContinuations false so writers never run consumer code.

open as a page

In an ASP.NET Core endpoint, why is `_ = Task.Run(...)` after a photo upload a poor way to render thumbnails, and what replaces it?

level: middleimportance: should knowfreq 48%

basics

~20 s

The task outlives the request: scoped services it captured are disposed, its exceptions go unobserved, the host neither tracks nor waits for it at shutdown, and a burst starts unlimited renders. A Channel drained by a BackgroundService replaces it.

open as a page

An ASP.NET Core billing app runs its nightly invoice-reminder BackgroundService on three replicas; why do customers get three reminders, and how do you fix it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Every replica is its own process whose host starts every registered hosted service, so three loops run three times. Fix it by running the job in one place, or by making each run claim its work in shared storage so duplicates do nothing.

open as a page

In ASP.NET Core 10, what happens to the whole app when a BackgroundService's ExecuteAsync throws an unhandled exception, and how should the loop be designed for it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The host logs the exception and, under the default BackgroundServiceExceptionBehavior.StopHost, stops the application, so every endpoint goes down with the loop. Catch failures per iteration inside the loop and let only truly fatal errors escape.

open as a page

An ASP.NET Core photo site queues thumbnail jobs in an in-memory Channel; why are jobs lost on deploys and crashes, and how do you drain them or make them durable?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Queued jobs exist only in process memory, so the queue is at-most-once: a crash, kill or overrun shutdown loses them. Drain on graceful stop by completing the writer and reading until empty; when loss is unacceptable, record each job durably first.

open as a page