TExcelTAD
Home › ASP.NET Core › Background Services

Background Services

Not every piece of work belongs inside a request. Sending e-mails, resizing images, cleaning old records or polling another system can run in the background while Kestrel keeps answering requests. ASP.NET Core apps run on the .NET Generic Host, which can start and stop long-running hosted services together with the web server.

IHostedService and BackgroundService

Type You implement Use when
IHostedService StartAsync and StopAsync short startup/shutdown work (warm a cache, register with a service)
BackgroundService one method: ExecuteAsync(CancellationToken) a loop that runs for the whole life of the app
IHostedLifecycleService (.NET 8+) extra hooks: StartingAsync, StartedAsync, StoppingAsync, StoppedAsync fine-grained ordering around startup/shutdown

A periodic job with BackgroundService and PeriodicTimer:

csharp
public class CleanupWorker(IServiceScopeFactory scopes, ILogger<CleanupWorker> logger)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
        do
        {
            // DbContext is scoped: create a scope for each run
            using var scope = scopes.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<NotesDb>();

            int removed = await db.Notes
                .Where(n => n.DeletedAt < DateTime.UtcNow.AddDays(-30))
                .ExecuteDeleteAsync(stoppingToken);
            logger.LogInformation("Cleanup removed {Count} notes", removed);
        }
        while (await timer.WaitForNextTickAsync(stoppingToken));
    }
}

// Program.cs
builder.Services.AddHostedService<CleanupWorker>();
bash · try it yourself
$ dotnet run --urls http://localhost:5000
info: CleanupWorker[0]
      Cleanup removed 3 notes
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/dev/NotesApi

Important rules:

  • Hosted services are singletons. To use scoped services such as a DbContext, inject IServiceScopeFactory and create a scope per unit of work.
  • Honour the stoppingToken. When the app shuts down (Ctrl+C, docker stop) the token is cancelled; the host waits up to HostOptions.ShutdownTimeout (30 s by default) for you to finish.
  • Catch exceptions. Since .NET 6, an unhandled exception in ExecuteAsync stops the whole host by default (BackgroundServiceExceptionBehavior.StopHost).
  • ExecuteAsync starts during startup; don't block before the first await, or the app won't start listening.

A queue between requests and workers

A common design: the endpoint drops a job into an in-memory queue and immediately returns 202 Accepted; a background service reads the queue and does the slow work. System.Threading.Channels provides a fast, thread-safe async queue:

csharp
builder.Services.AddSingleton(Channel.CreateBounded<EmailJob>(capacity: 100));
builder.Services.AddHostedService<EmailSender>();

app.MapPost("/signup", async (SignupDto dto, Channel<EmailJob> queue) =>
{
    await queue.Writer.WriteAsync(new EmailJob(dto.Email, "Welcome!"));
    return Results.Accepted();
});

public record EmailJob(string To, string Subject);

public class EmailSender(Channel<EmailJob> queue, ILogger<EmailSender> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        await foreach (var job in queue.Reader.ReadAllAsync(ct))
            logger.LogInformation("Sending '{Subject}' to {To}", job.Subject, job.To);
    }
}

Channels are part of the base library, so the producer/consumer idea runs as plain C#. The consumer finishes when the writer is completed — just like a worker that drains its queue at shutdown:

csharp · try it yourself
using System;
using System.Threading.Channels;
using System.Threading.Tasks;

var queue = Channel.CreateBounded<EmailJob>(capacity: 10);

// The "background service": reads until the channel is completed
async Task RunWorkerAsync()
{
    int sent = 0;
    await foreach (var job in queue.Reader.ReadAllAsync())
    {
        await Task.Delay(10);                       // pretend to talk to an SMTP server
        sent++;
        Console.WriteLine(
quot;[worker] sent '{job.Subject}' to {job.To}"); } Console.WriteLine(
quot;[worker] queue drained, {sent} e-mails sent"); } // The "endpoints": enqueue and return immediately foreach (var email in new[] { "ada@example.com", "ben@example.com", "cy@example.com" }) { await queue.Writer.WriteAsync(new EmailJob(email, "Welcome!")); } Console.WriteLine("[api] 3 jobs queued, responded 202 Accepted"); Task worker = RunWorkerAsync(); // in ASP.NET Core the host starts it for you queue.Writer.Complete(); // like shutdown: no more jobs await worker; // wait for the worker to finish record EmailJob(string To, string Subject);
[api] 3 jobs queued, responded 202 Accepted
[worker] sent 'Welcome!' to ada@example.com
[worker] sent 'Welcome!' to ben@example.com
[worker] sent 'Welcome!' to cy@example.com
[worker] queue drained, 3 e-mails sent

Cancellation in action

The stopping token is an ordinary CancellationToken. This demo cancels a worker loop after three iterations, deterministically, instead of relying on a timer:

csharp · try it yourself
using System;
using System.Threading;
using System.Threading.Tasks;

using var cts = new CancellationTokenSource();
int tick = 0;

async Task ExecuteAsync(CancellationToken stoppingToken)
{
    try
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            tick++;
            Console.WriteLine(
quot;working... tick {tick}"); if (tick == 3) cts.Cancel(); // simulate Ctrl+C after the 3rd tick await Task.Delay(5, stoppingToken); } } catch (OperationCanceledException) { Console.WriteLine("stopping token cancelled"); } Console.WriteLine("cleanup done, worker exits"); } await ExecuteAsync(cts.Token);
working... tick 1
working... tick 2
working... tick 3
stopping token cancelled
cleanup done, worker exits

Note: An in-memory queue loses its jobs if the process crashes or restarts. For work that must not be lost, use a durable queue (Azure Service Bus, RabbitMQ, a database table) or a job library such as Hangfire or Quartz.NET.

Worker services without a web server

The same BackgroundService classes power the Worker Service template (dotnet new worker), a console host with DI, configuration and logging but no Kestrel — ideal for queue consumers and scheduled jobs in containers.

Test yourself

How should a BackgroundService use a scoped DbContext?

  1. Inject DbContext directly into the constructor
  2. Make the DbContext a singleton
  3. Inject IServiceScopeFactory and create a scope per unit of work
  4. Use new DbContext() once in the constructor and keep it forever

What happens by default (.NET 6+) when ExecuteAsync throws an unhandled exception?

  1. The exception is ignored
  2. The host stops
  3. The service restarts automatically
  4. Kestrel returns 500 to every request

Why does a queue-backed signup endpoint return 202 Accepted?

  1. The work was accepted and will finish later
  2. The e-mail was already delivered
  3. The request was invalid
  4. 202 is required for POST