Background Jobs in .NET: IHostedService and Worker Services

Build background jobs in .NET with BackgroundService and IHostedService: worker template, scoped services, PeriodicTimer, Channel queues, graceful stop.

Executive Summary: Background jobs in .NET run as hosted services: classes implementing IHostedService, usually via the BackgroundService base class, that the host starts at boot and stops at shutdown. The three problems every worker must solve are lifetime (scoped services like DbContext cannot be injected into the singleton worker; create a scope per iteration), stopping (a CancellationToken that fires at shutdown, with PeriodicTimer and Task.Delay honoring it automatically), and idempotency (a crash after doing the work but before recording it means the work runs twice).

The bug that teaches this topic usually arrives as a mystery. A user uploads a file, the endpoint queues “the processing” by calling a method and not awaiting it, the container deploys two minutes later. The file never gets processed. No error, no log line, no job. The task died with the request or the process, and this is the exact gap hosted services fill. Work whose lifetime belongs to the application, not to an HTTP request.

Background jobs in .NET means the built-in hosting model: IHostedService for start and stop hooks, BackgroundService for long-running loops, the worker template for worker-only apps, and Channel<T> for in-process queues. The hosted services documentation and the worker services guide are the official references.

The examples assume .NET SDK 10.0 with C# 14 and build an overdue-task reminder worker for the TaskApi. Two prerequisites matter: service lifetimes, because workers are singletons that touch scoped services (the dependency injection guide owns that rule), and cancellation tokens, which the async guide covers in depth.

Maintaining several worker fleets taught me this: the loop is the easy 20 percent. Lifetime, shutdown, and idempotency are the 80 percent that decide whether a worker is trustworthy in production.

IHostedService: the contract the host calls

IHostedService is two methods the host calls at lifecycle boundaries: StartAsync when the application starts and StopAsync when it shuts down. Register any implementation in the container and the generic host finds and runs it, in registration order. Web apps and worker-only apps run on the same host, which is why the same model powers background work in a web API and in a standalone worker process.

Nobody implements the raw interface for loops, because it leaves the threading to you. The base class everyone uses is BackgroundService, which turns “a service that runs in the background” into “a method that loops until cancelled”:

public abstract class BackgroundService : IHostedService
{
    protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

    // StartAsync runs ExecuteAsync; StopAsync cancels the token and waits.
}

The worker template

A dedicated worker process starts with one command, and the template wires the generic host, the service, and the container together:

dotnet new worker -o TaskApi.Worker
// TaskApi.Worker/Program.cs (template, lightly edited)
var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddHostedService<OverdueTaskWorker>();

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

The same AddHostedService<T>() line works inside the web API’s Program.cs, which is how the TaskApi can run its reminder worker in-process or as a separate deployment with no code change.

A complete BackgroundService with PeriodicTimer

The reminder worker wakes up every hour, finds overdue tasks, and sends notifications. PeriodicTimer, built for exactly this, waits efficiently and honors the stopping token:

public sealed class OverdueTaskWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<OverdueTaskWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromHours(1));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                await SendOverdueRemindersAsync(stoppingToken);
            }
            catch (OperationCanceledException)
            {
                break;                       // shutdown: leave the loop cleanly
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Overdue reminder pass failed");
            }
        }
    }

    private async Task SendOverdueRemindersAsync(CancellationToken ct)
    {
        using var scope = scopeFactory.CreateScope();     // see next section
        var db = scope.ServiceProvider.GetRequiredService<TaskApiContext>();

        var overdue = await db.Tasks
            .Where(t => !t.Done && t.DueDate < DateTime.UtcNow)
            .ToListAsync(ct);

        foreach (var task in overdue)
        {
            logger.LogInformation("Reminder: task {Title} is overdue", task.Title);
        }
    }
}

Three decisions in this loop carry all the weight. The timer’s wait honors the stopping token, so shutdown is instant even mid-sleep. The catch block separates cancellation (normal shutdown) from failures (logged, loop continues). Exceptions never propagate out of ExecuteAsync except cancellation, because an escaping exception silently kills the worker for the rest of the process’s life.

Scoped services inside a singleton worker

Here is the lifetime trap from the DI guide, in its most common production shape: a BackgroundService is registered once, so it is a singleton, and a DbContext is scoped. Injecting the context into the worker’s constructor creates a captive dependency: one context shared across every iteration and, if a second service also uses it, every request.

WRONG:

public sealed class OverdueTaskWorker(TaskApiContext db) : BackgroundService
// ^ a singleton holding a scoped DbContext forever: shared state, stale tracking

RIGHT: create a scope per unit of work, through IServiceScopeFactory:

using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<TaskApiContext>();

Each pass gets a fresh context, disposes it when the scope ends, and nothing leaks across iterations. This pattern is the standard shape in every hosted service that touches scoped services.

In-process queues with Channel<T>

The other common shape is producer-consumer: the request path enqueues lightweight work items, and a worker consumes them. Channel<T> is the built-in primitive, a thread-safe queue with async reads:

// registration: one bounded channel shared by producer and consumer
builder.Services.AddSingleton(Channel.CreateBounded<TaskSummary>(
    new BoundedChannelOptions(1000) { FullMode = BoundedChannelFullMode.Wait }));

// producer: an endpoint enqueues without blocking the request
public async Task<IActionResult> Export(TaskSummary summary)
{
    await _taskChannel.Writer.WriteAsync(summary);
    return Accepted();
}

// consumer: the worker drains the queue
await foreach (var item in _taskChannel.Reader.ReadAllAsync(stoppingToken))
{
    // process each item, with per-item scopes for scoped services
}

A bounded channel protects the process. When the queue is full, writers wait (or drop, per the full-mode setting) instead of letting memory grow without limit, which is the failure mode of every unbounded queue. Be honest about the channel’s contract, though: it lives in memory, so items in it at crash time are lost. That is acceptable for reminders and re-derivable work, and unacceptable for payments, which is exactly the line the idempotency section draws. The Channel API documentation covers the reader and writer variants.

Graceful stop: shutdown is part of the design

At shutdown the host cancels the stopping token and waits a fixed window for hosted services to finish. The default is 30 seconds through HostOptions.ShutdownTimeout, configurable when your work needs more or less. The worker’s obligations:

  • Pass the token into every wait and call. PeriodicTimer.WaitForNextTickAsync(token) and Task.Delay(interval, token) wake immediately on cancel; Thread.Sleep never does.
  • Treat cancellation as normal. Catch OperationCanceledException, stop the loop, and return. Rethrowing it or logging it as an error makes every deploy look like a failure.
  • Finish or abandon cleanly. Within the shutdown window, either complete the in-flight item or record it as unfinished. The choice belongs in the code, not in a crash.

In containers and Kubernetes, SIGTERM is what triggers this token. So a well-behaved worker is also a pod that drains properly, which the guide on running .NET in Kubernetes covers from the platform side.

Idempotency: at least once means maybe twice

An in-process worker offers no delivery guarantees. If the process dies between doing the work and marking it done, the next pass does the work again. As a result, every recurring handler must be safe to run twice:

  • Natural keys. Mark reminders sent by task id and timestamp range, not by a boolean, so a second pass recognizes completed work.
  • Upserts and stateless effects. Prefer operations whose result is the same when repeated. Sending “your task is overdue” twice is tolerable, charging a card twice is not.
  • Own the retry decision. A failing item that stays in the queue forever becomes poison; retry counts and dead-letter handling (park the item somewhere inspectable) are part of the loop.

This is the boundary where teams graduate to durable systems: when a job must survive the process, use a durable queue (RabbitMQ, Azure Service Bus, or similar). Hangfire and Quartz deserve a mention as in-process-plus-database options, with scheduling and retry features the hand-rolled loop does not have. Evaluate them against the “is this job allowed to vanish on deploy” test before choosing in-process.

How real systems do this

  • Workers log with structure and context. Every pass logs its item count and duration at information level, failures at error level with the item id, using the same structured logging the Serilog guide sets up. This means “is the worker running?” is answered by a log query, not a guess.
  • Workers are unit testable. The loop delegates to a method that takes a scope’s services and a token. As a result, tests call the method with a fake scope and verify behavior without hosting the worker.
  • One worker, one job. Teams register multiple small hosted services instead of one god-loop, because start/stop, logging, and failure isolation all behave better at small scale.

A loss I remember watching happen live: a service processed exports with a fire-and-forget task, an unawaited method call with the result going nowhere. A routine deploy two minutes after a large export started killed the job with no trace, and the user’s ticket said “it just never finished”. The work moved to a hosted service with an items table, and the same failure became a visible, restartable row. The lesson: if the work matters, it belongs to a lifecycle the application owns, and fire-and-forget is the only background pattern with no lifecycle at all.

Decision framework: which background shape fits

  1. Can the job run inside the process, or must it survive deploys? Surviving deploys means a durable queue or scheduler. In-process hosted services are for work that tolerates a pause.
  2. Is the trigger time or an event? Time: PeriodicTimer in a loop. Events from the same process: Channel<T> producer-consumer. Events from other systems: a durable message queue.
  3. Does it need scoped services? Scope per item via IServiceScopeFactory; never inject scoped services into the worker constructor.
  4. Is the handler idempotent? If not, make it so before shipping the worker. At-least-once is the right delivery guarantee for any process that can restart.
  5. One worker or one big one? One hosted service per job: isolated stopping, logging, and failure are worth the extra files.

When NOT to use a hosted service

  • When losing a job is unacceptable. Payments, order fulfillment, and contractual notifications belong on durable infrastructure with persistence and dead-lettering. An in-memory worker is the wrong promise.
  • When the “job” is one line after a request. Work that completes within the request’s lifetime and has no retry story is just awaited code. Queuing adds a lifecycle to manage for nothing.
  • When a cron schedule is already managed. If your platform already schedules jobs (database schedulers, Kubernetes CronJobs, Hangfire or Quartz installations), one more in-process timer is one more system to monitor.

Common mistakes

  • Injecting a DbContext into the worker. A singleton holding a scoped service shares state across iterations and requests. Create a scope per unit of work.
  • Blocking sleeps. Thread.Sleep and Task.Delay without the token ignore shutdown and stall the host’s stop window. PeriodicTimer and tokened delays are the correct waits.
  • Escaping exceptions in ExecuteAsync. An exception that leaves the loop kills the worker silently until the next deploy. Catch per-iteration, log, continue, and only let cancellation exit the loop.
  • Unbounded channels. Every unbounded queue eventually outgrows memory under a burst; bound the channel and choose what writers do when it is full.
  • Non-idempotent handlers. Any restart can re-run in-flight work; natural keys and repeated-safe operations are the mitigation, not hope.
  • Business logic in the loop body. The worker should orchestrate (scope, read, delegate). Rules belong in services it calls, which keeps the loop testable and the rules unit-testable.

Key takeaways

  • IHostedService is the start/stop contract; BackgroundService is the loop base class; AddHostedService<T>() registers either in web apps and worker processes alike.
  • PeriodicTimer gives time-triggered workers an efficient, token-honoring wait; Channel<T> (bounded) gives producer-consumer work an in-process queue.
  • Workers are singletons: create a scope per unit of work for scoped services like DbContext, never inject them into the constructor.
  • Shutdown is designed: pass the stopping token everywhere, treat OperationCanceledException as normal exit, and know your HostOptions.ShutdownTimeout.
  • Assume every handler can run twice; natural keys and idempotent effects are what make at-least-once delivery safe.
  • In-process work pauses on deploys. Jobs that must survive use durable queues, with Hangfire and Quartz as the in-process-plus-database alternatives for scheduling and retries.

FAQ

What is an IHostedService in .NET?

An interface with StartAsync and StopAsync that the generic host calls during application startup and shutdown. Register an implementation with AddHostedService and the host manages its lifecycle. It suits start-and-finish startup work, and long-running loops usually derive from BackgroundService, which implements IHostedService for you.

What is a BackgroundService in .NET?

A base class implementing IHostedService that gives you one method to write: ExecuteAsync with a stopping token, running for the lifetime of the application. You write a loop, typically with PeriodicTimer or a Channel reader, and the class handles start-up and stop mechanics around it.

How do I use a DbContext in a background worker?

Inject IServiceScopeFactory, create a scope for each unit of work with CreateScope, resolve the DbContext from that scope. Dispose it when the work ends. Never inject the context into the worker constructor: workers are singletons and DbContext is scoped, so direct injection captures one instance forever.

What is Channel<T> used for in .NET?

A built-in thread-safe queue for producer-consumer scenarios. Producers write with WriteAsync, a consumer reads with ReadAllAsync, and a bounded channel applies backpressure when full. It is an in-process queue: fast and dependency-free, but items in it are lost if the process dies. That is why durable queues exist for work that must survive.

How long does the host wait for a worker to stop?

The default is 30 seconds, set through HostOptions.ShutdownTimeout, and it is configurable in either direction. The host cancels the stopping token and waits that window. A worker that honors the token finishes immediately, and one that blocks its stop forces the host to abort it at the timeout.

Give the work a lifecycle you own

Background work stops being scary the moment it stops being invisible: a hosted service with a scoped, token-honoring, idempotent loop is a normal, testable part of the application, and fire-and-forget tasks are the only pattern with no story at all. Build the loop, own the stop, assume the retry, and reach for durable infrastructure when the work’s value crosses the line memory cannot hold. The operations track comes next with logging in .NET with Serilog, and every guide in the series lives on the .NET series index. The rule of thumb: if the work matters, it has a lifecycle, a token, and an idempotent handler, or it belongs to a queue that does.

Last updated on 21 November 2026

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *