Background jobs
Background jobs move slow work (emails, reports, file processing) out of the HTTP request. In ASP.NET Core you build them with BackgroundService, feed them through a queue, and must handle DI scopes, errors and shutdown correctly.
62.1 Why is it used?
- In the demo the order API waits for a 2 s SMTP call, so every order takes 2.3 s.
- If SMTP is slow the API is slow; if the email fails the order fails too.
- The customer does not need to wait for the invoice email.
- Fix: the request puts work in a queue and returns at once; a worker does it in the background.
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddScoped<EmailSender>();var app = builder.Build(); var nextId = 1000;app.MapPost("/orders", async (OrderRequest req, EmailSender email) =>{ var id = Interlocked.Increment(ref nextId); var order = new OrderPlaced(id, req.Email); await email.SendAsync(order, CancellationToken.None); return Results.Ok(order);});app.Run();Output
$ curl -i localhost:5062/orders \ -H "Content-Type: application/json" \ -d '{"email":"riya@example.com"}' \ -w 'time: %{time_total}s'HTTP/1.1 200 OK{"orderId":1001,"email":"riya@example.com"}time: 2.326506s62.2 Worker template: BackgroundService
- dotnet new worker gives a ready Worker class.
- Worker inherits BackgroundService; ExecuteAsync is called once when the app starts.
- The loop runs until stoppingToken is cancelled (Ctrl+C, deploy).
- Register it with AddHostedService<Worker>(); it also works inside a web app.
C#
public class Worker(ILogger<Worker> logger) : BackgroundService{ protected override async Task ExecuteAsync( CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { logger.LogInformation( "Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } }}Output
$ dotnet new worker -n ReportWorker$ dotnet runinfo: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: ReportWorker.Worker[0] Worker running at: 11/07/2026 02:45:27 +05:30info: ReportWorker.Worker[0] Worker running at: 11/07/2026 02:45:28 +05:30^Cinfo: Microsoft.Hosting.Lifetime[0] Application is shutting down...62.3 Queue: a Channel wrapper
- Channel<T> is a thread-safe producer/consumer queue.
- CreateBounded(100): capacity 100, so memory cannot grow without limit (writers wait when full).
- EnqueueAsync writes an order, ReadAllAsync hands orders to the worker one by one.
- Register the queue as a singleton so the endpoint and the worker share the same instance.
C#
using System.Threading.Channels; public class EmailQueue{ private readonly Channel<OrderPlaced> channel = Channel.CreateBounded<OrderPlaced>(100); public ValueTask EnqueueAsync( OrderPlaced order) => channel.Writer.WriteAsync(order); public IAsyncEnumerable<OrderPlaced> ReadAllAsync(CancellationToken ct) => channel.Reader.ReadAllAsync(ct);}62.4 Enqueue and return 202
- AddSingleton<EmailQueue>, AddHostedService<EmailWorker>.
- The endpoint no longer sends the email; it only enqueues.
- Results.Accepted returns 202: the request was accepted, the work happens later.
- Response time went from 2.3 s to 17 ms.
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<EmailQueue>();builder.Services.AddScoped<EmailSender>();builder.Services.AddHostedService<EmailWorker>();var app = builder.Build();var nextId = 1000;app.MapPost("/orders", async (OrderRequest req, EmailQueue queue) =>{ var id = Interlocked.Increment(ref nextId); var order = new OrderPlaced(id, req.Email); await queue.EnqueueAsync(order); return Results.Accepted(value: order);});app.Run();Output
$ curl -i localhost:5062/orders \ -H "Content-Type: application/json" \ -d '{"email":"aman@example.com"}' \ -w 'time: %{time_total}s'HTTP/1.1 202 Accepted{"orderId":1002,"email":"aman@example.com"}time: 0.017408s- Step 1
1.POST /orders: endpoint creates the order
- Step 2
2.queue.EnqueueAsync(order) writes it to a bounded Channel (singleton)
- Step 3
3.Endpoint returns 202 Accepted in ~17 ms
- Step 4
4.EmailWorker (BackgroundService) reads with await foreach
- Step 5
5.New scope per order: fresh scoped EmailSender
- Step 6
6.Invoice email sent; scope disposed
202 means "accepted for later", not "done"
62.5 Scoped services in a worker
- First attempt: EmailWorker asks for the scoped EmailSender in its constructor.
- Every hosted service is a singleton, so this is a captive dependency and the app fails at startup.
- Fix: inject IServiceScopeFactory (itself a singleton) and call CreateScope() per job.
- Get a fresh EmailSender from scope.ServiceProvider; using disposes the scope when the order is done.
- Same rule for DbContext: one scope per job.
C#
public class EmailWorker(EmailQueue queue, EmailSender sender) : BackgroundService{ protected override async Task ExecuteAsync( CancellationToken stoppingToken) { await foreach (var order in queue.ReadAllAsync(stoppingToken)) { await sender.SendAsync(order, stoppingToken); } }}Output
$ dotnet run --urls http://localhost:5062Unhandled exception. System.AggregateException:Some services are not able to be constructed... Cannot consume scoped service 'EmailSender'from singleton'Microsoft.Extensions.Hosting.IHostedService'.C#
// ctor: EmailQueue, IServiceScopeFactoryprotected override async Task ExecuteAsync( CancellationToken stoppingToken){ await foreach (var order in queue.ReadAllAsync(stoppingToken)) { using var scope = scopes.CreateScope(); var sender = scope.ServiceProvider .GetRequiredService<EmailSender>(); await sender.SendAsync(order, stoppingToken); }}Output
info: EmailSender[0] Sending invoice for order 1001info: EmailSender[0] Invoice sent to riya@example.cominfo: EmailSender[0] Sending invoice for order 1002info: EmailSender[0] Invoice sent to aman@example.com62.6 Graceful shutdown
- On deploy or Ctrl+C the stoppingToken is cancelled.
- If that token is also passed to SendAsync, the email in progress is silently cancelled.
- Pass CancellationToken.None for the current job so it finishes; the token on ReadAllAsync only stops waiting for new items.
- The host waits 30 s by default; change it with HostOptions.ShutdownTimeout.
C#
await foreach (var order in queue.ReadAllAsync(stoppingToken)){ using var scope = scopes.CreateScope(); var sender = scope.ServiceProvider .GetRequiredService<EmailSender>(); // let the current email finish await sender.SendAsync(order, CancellationToken.None);}Output
# SendAsync(order, stoppingToken)info: EmailSender[0] Sending invoice for order 1001^Cinfo: Microsoft.Hosting.Lifetime[0] Application is shutting down... # SendAsync(order, CancellationToken.None)info: EmailSender[0] Sending invoice for order 1001^Cinfo: Microsoft.Hosting.Lifetime[0] Application is shutting down...info: EmailSender[0] Invoice sent to riya@example.com62.7 Errors: 202 does not mean sent
- A wrong email (riya.example.com) still gets 202, because 202 only means "queued".
- The worker throws two seconds later and the client never finds out.
- No try/catch in the loop: since .NET 6 the default BackgroundServiceExceptionBehavior is StopHost, so one bad email takes the whole API down.
- Wrap every job in its own try/catch and log: order 1001 fails, order 1002 still goes out.
Output
$ curl -i localhost:5062/orders \ -H "Content-Type: application/json" \ -d '{"email":"riya.example.com"}'HTTP/1.1 202 Accepted{"orderId":1001,"email":"riya.example.com"} fail: Microsoft.Extensions.Hosting.Internal.Host[9] BackgroundService failed System.InvalidOperationException: Bad email: riya.example.comC#
await foreach (var order in queue.ReadAllAsync(stoppingToken)){ try { await SendAsync(order); } catch (Exception ex) { logger.LogError(ex, "Email failed for order {Id}", order.OrderId); }}62.8 Comparison: ways to run background work
| Option | Where jobs live | Good for | Limit |
|---|---|---|---|
| Task.Run fire-and-forget | Nowhere (host does not know) | Nothing in production | Stopped on shutdown, exceptions lost, request scope disposed |
| BackgroundService + Channel | In-memory queue | Fast in-process work (emails, thumbnails) | Pending jobs lost on crash/deploy |
| BackgroundService + PeriodicTimer | No queue, a timer loop | Simple repeating work | No persistence, no retries |
| Hangfire | Database | Durable jobs, automatic retries, dashboard | Needs storage, extra package |
| Quartz.NET | Memory or DB | Schedules and cron triggers | More setup |
62.9 Common mistakes
- Fire-and-forget Task.Run in the endpoint: the host does not know about it, nobody sees its exception, and DbContext from the request scope is already disposed.
- Injecting a scoped service into a hosted service constructor (captive dependency).
- No try/catch per job: one exception stops the host.
- Passing stoppingToken into the job itself: shutdown cancels work halfway.
- Unbounded queue: memory grows without limit under load.
- Treating an in-memory Channel as durable: jobs are lost on crash; use Hangfire for that.
62.10 Interview tips
- "I build a worker with BackgroundService and register it with AddHostedService."
- The request writes to a bounded Channel and returns 202; the worker reads with await foreach.
- A hosted service is a singleton, so I create a new scope per job with IServiceScopeFactory.
- Handle graceful shutdown with stoppingToken, try/catch every job.
- For durable or scheduled jobs: Hangfire (DB, retries, dashboard) or Quartz.NET (cron).