Lesson 19 of 40 Backend Services Intermediate 55 min

Background Services & Workers

In this lesson, you will learn how .NET background services and worker processes handle tasks that run outside the normal request-response flow. These are essential for recurring jobs, queue processing, cleanup routines, and many cloud-based workloads.

← Back to Visual Studio 2026 Tutorial Home

What you will learn

Why this matters: Not all work should happen during a user request. Long-running tasks, scheduled jobs, and queue consumers often belong in background processes so your application stays responsive and scalable.

Part 1: What is a background service?

A background service is a task that continues running after the application starts. Unlike controller actions or page handlers, it is not triggered directly by a user request. Instead, it performs ongoing or repeated work behind the scenes.

Common examples include:

Key idea: A background service should be designed to start cleanly, stop gracefully, and recover safely from temporary failures.

Part 2: Using BackgroundService

The most common way to create a worker in .NET is to inherit from BackgroundService and implement ExecuteAsync. This gives you a clear lifecycle and integrates well with hosting and dependency injection.

public class EmailWorker : BackgroundService { private readonly ILogger _logger; public EmailWorker(ILogger logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Checking for pending emails..."); await ProcessEmailsAsync(stoppingToken); await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } private Task ProcessEmailsAsync(CancellationToken stoppingToken) { return Task.CompletedTask; } }

This pattern is simple and effective, but it must be designed carefully so the loop does not become unstable, noisy, or wasteful.

Part 3: Cancellation and graceful shutdown

Background services should stop cleanly when the application shuts down. That is why the CancellationToken passed into ExecuteAsync is so important.

A service that ignores cancellation can delay application shutdown or leave background work in an unpredictable state.

Part 4: Error handling and retries

Background tasks often depend on networks, databases, queues, or APIs, which means failures are normal. A well-designed worker should expect temporary problems and respond carefully.

Concern Recommended approach
Temporary API failure Retry with delay or backoff
Unexpected exception Log clearly and prevent silent failure
Repeated failure Escalate, alert, or move work aside for later review
Bad input data Handle separately instead of crashing the worker loop
Important: A worker should not collapse entirely because one message, record, or external call failed.

Part 5: Scheduled work vs queue-based work

Not all background processing looks the same. Some workers run on a timer, while others respond to new work from a queue or stream.

Choosing the right model helps keep the application efficient and easier to reason about.

When to use a worker service

Scenario Why a worker is useful
Email sending Removes delay from user-facing requests
Queue processing Lets background jobs be handled independently
Recurring refresh tasks Keeps data or cache updated regularly
External synchronization Handles long-running integration tasks safely

A practical worker workflow

Step 1: Define whether the work is scheduled, queued, or continuous
Step 2: Implement the worker with cancellation support
Step 3: Add clear structured logging
Step 4: Protect external calls with retries or fallback logic
Step 5: Keep each processing cycle focused and measurable
Step 6: Test startup, failure, and shutdown behavior

Best practices

Summary

In this lesson, you learned how background services and worker processes handle long-running or recurring tasks, why cancellation and resilience matter, and how to design workers that fit modern .NET systems.

In the next lesson, you will move into authentication and authorization.