Lesson 7 of 8
IHostedService & Background Workers
IHostedService and BackgroundService run long-lived tasks alongside your HTTP server: email queues, scheduled jobs, metrics aggregation, and message queue consumers. They are managed by the .NET host lifecycle - started on startup and gracefully stopped on shutdown.
BackgroundService - Queue-based Email Sender
using Microsoft.Extensions.Hosting;
// ━━ Background task queue - thread-safe channel ━━
public interface IEmailTaskQueue
{
void Enqueue(EmailTask task);
Task<EmailTask> DequeueAsync(CancellationToken ct);
}
public class EmailTaskQueue : IEmailTaskQueue
{
private readonly System.Threading.Channels.Channel<EmailTask> _channel =
System.Threading.Channels.Channel.CreateBounded<EmailTask>(
new System.Threading.Channels.BoundedChannelOptions(100)
{
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait
});
public void Enqueue(EmailTask task) => _channel.Writer.TryWrite(task);
public async Task<EmailTask> DequeueAsync(CancellationToken ct) =>
await _channel.Reader.ReadAsync(ct);
}
// ━━ Background service that processes the queue ━━
public class EmailBackgroundService(
IEmailTaskQueue queue,
IServiceScopeFactory scopeFactory,
ILogger<EmailBackgroundService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Email background service started");
while (!stoppingToken.IsCancellationRequested)
{
try
{
var task = await queue.DequeueAsync(stoppingToken);
// Create scope for scoped services (EF Core, etc.)
using var scope = scopeFactory.CreateScope();
var emailService = scope.ServiceProvider.GetRequiredService<IEmailService>();
await emailService.SendAsync(task, stoppingToken);
logger.LogInformation("Email sent to {To}", task.To);
}
catch (OperationCanceledException)
{
break; // graceful shutdown
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to process email task");
// Don't rethrow - keep service running
await Task.Delay(5000, stoppingToken); // back-off on error
}
}
logger.LogInformation("Email background service stopped");
}
}
// ━━ Registration ━━
builder.Services.AddSingleton<IEmailTaskQueue, EmailTaskQueue>();
builder.Services.AddHostedService<EmailBackgroundService>();
// ━━ Enqueue from controller - fire-and-forget safely ━━
public class OrderController(IEmailTaskQueue emailQueue) : ControllerBase
{
[HttpPost("{id}/confirm")]
public async Task<IActionResult> ConfirmOrder(string id, [FromServices] IOrderService orders)
{
var order = await orders.ConfirmAsync(id);
emailQueue.Enqueue(new EmailTask(order.CustomerEmail, "Order Confirmed", $"Order {id} confirmed"));
return Ok(order);
}
}
public record EmailTask(string To, string Subject, string Body);
interface IEmailService { Task SendAsync(EmailTask task, CancellationToken ct); }
interface IOrderService { Task<dynamic> ConfirmAsync(string id); }Tip
Tip
Practice IHostedService Background Workers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of IHostedService Background Workers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with IHostedService Background Workers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?