Background & Hosted Services
Background processing lets an application do meaningful work—emails, media pipelines, cleanup, retries—without blocking a request or depending on a client staying connected.
Overview
The .NET Generic Host starts registered IHostedService instances, coordinates BackgroundService execution, propagates cancellation, and gives each service a bounded graceful-shutdown window. In-process workers suit lifecycle-bound loops, polling, telemetry, and best-effort local queues; they do not make accepted work durable. A bounded Channel can separate producers and consumers while applying backpressure, but pending items disappear when the process fails. Durable schedulers, databases, or brokers are required for work that must survive restart, coordinate replicas, run once according to a business schedule, or support operator replay. Hosted services are singletons, so each item creates and disposes its own dependency-injection scope. Production loops avoid overlapping timers, propagate cancellation, isolate item failures, bound retries and concurrency, make effects idempotent, expose progress and oldest-work age, stop admission before drain, and checkpoint unfinished durable work before the shutdown deadline.
What you will learn
- Understand host lifecycle and BackgroundService exceptions.
- Build cancellable loops and periodic work.
- Use bounded Channels for backpressure.
- Create scoped dependencies per item.
- Choose local or durable storage.
- Operate retries, health, drain, and shutdown.
Prerequisites
- Generic Host, DI, async C#, cancellation, and logging.
- Queue, retry, idempotency, health, and deployment basics.
- A durability requirement.
When to use Background & Hosted Services
Good fit
- Work belongs to the app lifecycle.
- Local work tolerates process loss.
- A worker consumes a durable queue.
Choose another approach when
- Requests start fire-and-forget work.
- Local work must survive restart.
- Independent scaling needs another deployment.
Key concepts
Hosted services participate in startup and shutdown.
ExecuteAsync owns a cancellable loop.
Channels create backpressure.
Singleton workers create scopes per item.
PeriodicTimer avoids overlap.
Local queues lose work on crash.
Repeated work must not duplicate effects.
Progress, cancellation, and checkpointing define safe operation.
Architecture
A producer enqueues durable job records; one or more workers claim and process them, writing results back to the same store they were claimed from.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The sample uses a bounded Channel, cancellation, graceful completion, and failure isolation.
- 01Define durability
Decide loss and retry semantics.
- 02Choose lifecycle
Select service, timer, or scheduler.
- 03Bound admission
Apply capacity and backpressure.
- 04Create scopes
Resolve scoped services per item.
- 05Handle failure
Retry and isolate poison work.
- 06Shut down
Stop admission and drain or checkpoint.
- 07Observe
Measure depth, age, duration, and progress.
Code example
Register a recurring job alongside its dependencies so scheduling and business logic stay in one discoverable place.
public static class ExportModule
{
public static IServiceCollection AddExportJobs(this IServiceCollection services)
{
services.AddScoped<IReportExporter, ReportExporter>();
return services;
}
public static void MapExportJobs(this IRecurringJobManager jobs)
{
jobs.AddOrUpdate<IReportExporter>(
"nightly-export",
exporter => exporter.ExportAsync(CancellationToken.None),
Cron.Daily(hour: 2));
}
}Testing strategy
Test lifecycle and failure behavior.
- Test bounded admission.
- Cancel idle and active work.
- Isolate item failures.
- Verify scope disposal.
- Test drain timeout.
- Restart durable work idempotently.
Security considerations
Workers execute with service privilege.
- Use least privilege.
- Validate tenant and size.
- Do not capture request credentials.
- Redact payloads.
- Protect replay controls.
Performance and scalability
Concurrency matches dependency capacity.
- Bound queues.
- Tune consumers.
- Avoid tight polling.
- Batch carefully.
- Track oldest age.
Deployment and operations
Workers stop and resume predictably.
- Set shutdown grace.
- Stop readiness before drain.
- Coordinate singleton schedules.
- Checkpoint progress.
- Test backlog recovery.
Common problems and fixes
Worker stops.
Likely cause: Unhandled exception.
Fix: Isolate failures.
Memory grows.
Likely cause: Unbounded queue.
Fix: Bound capacity.
Scoped errors.
Likely cause: A scoped service was captured.
Fix: Create per-item scopes.
Jobs overlap.
Likely cause: Timer reentry.
Fix: Use a sequential loop.
Deploy loses work.
Likely cause: Queue is local.
Fix: Use durable storage.
Shutdown hangs.
Likely cause: Cancellation is ignored.
Fix: Propagate tokens and cap drain.
Best practices
- Use cancellable loops.
- Use bounded Channels.
- Create scopes per item.
- Use PeriodicTimer.
- Use durable storage when required.
- Make effects idempotent.
- Bound retries.
- Measure age and shutdown.
Production checklist
- Durability is explicit.
- Admission and concurrency are bounded.
- Cancellation propagates.
- Scopes are per item.
- Effects are idempotent.
- Poison work is isolated.
- Age and progress alert.
- Shutdown and recovery are rehearsed.
Common interview questions
IHostedService versus BackgroundService?
BackgroundService wraps an ExecuteAsync loop.
Why bounded Channel?
To apply backpressure.
How use scoped services?
Create a scope per item.
Unhandled exception?
The task stops and host policy applies.
When durable queue?
When work must survive restart.
Avoid overlapping schedules?
Use sequential PeriodicTimer or coordination.
Graceful shutdown?
Stop admission and drain or checkpoint within grace.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Hosted Work Queue
A .NET 10 bounded Channel work queue demonstrating backpressure, cancellation, graceful drain, and per-item failure isolation.
- Run
dotnet run --project src/HostedWorkQueue- Test
dotnet test HostedWorkQueue.slnx