Background services are commonly used in ASP.NET Core applications to execute tasks that should run independently of incoming HTTP requests.
Examples include sending scheduled notifications, processing queued messages, synchronizing data, generating reports, cleaning up expired records, and executing recurring database operations.
ASP.NET Core provides the BackgroundService base class, which makes it relatively straightforward to implement these long-running operations.
However, there is one problem developers sometimes encounter in production: a single exception can stop the entire background service and, depending on the hosting configuration, even stop the application.
Imagine a background service that runs every five minutes to process pending notifications.
The first execution completes successfully. During the second execution, the database becomes temporarily unavailable. The service throws an exception, and the execution loop terminates.
The application might still be running in some configurations, but the background service is no longer processing notifications.
This creates a situation where the application appears healthy, while an important background operation has silently stopped.
The problem becomes more serious when the background service is responsible for business-critical operations such as payment processing, scheduled reminders, inventory synchronization, or message processing.
A common mistake is to catch every exception and ignore it. Although this might prevent the service from stopping, it can hide genuine problems and leave failed jobs unprocessed.
The better approach is to handle failures at the appropriate level, log meaningful information, retry operations when appropriate, and allow the background service to continue processing subsequent jobs.
In this article, we'll understand how BackgroundService handles exceptions, why an unhandled exception can stop the host, and how to build more resilient background workers using practical C# examples.
We'll also explore retry strategies, cancellation handling, dependency injection scopes, logging, and production considerations.
Understanding How BackgroundService Works
Before looking at exception handling, let's understand how BackgroundService works in ASP.NET Core.
BackgroundService is an abstract class that implements IHostedService. It provides a convenient way to implement long-running background operations.
A typical background service overrides the ExecuteAsync() method:
public class NotificationBackgroundService : BackgroundService
{
private readonly ILogger<NotificationBackgroundService> _logger;
public NotificationBackgroundService(
ILogger<NotificationBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Background service is running.");
await Task.Delay(
TimeSpan.FromMinutes(5),
stoppingToken);
}
}
}The ExecuteAsync() method represents the lifetime of the background service.
As long as the returned task is running, the hosted service remains active.
In this example, the service executes a loop, writes a log message, waits for five minutes, and then repeats the operation.
The stoppingToken is provided by the hosting infrastructure. It is triggered when the application begins shutting down.
The service should observe this token and stop its work gracefully.
Register the background service in Program.cs:
builder.Services.AddHostedService<NotificationBackgroundService>();ASP.NET Core starts the service when the application starts and manages its lifecycle during application shutdown.
This is the basic structure of a BackgroundService.
The important part is understanding what happens when an exception escapes from ExecuteAsync().
What Happens When an Exception Occurs in BackgroundService?
Consider the following implementation:
public class NotificationBackgroundService : BackgroundService
{
private readonly ILogger<NotificationBackgroundService> _logger;
public NotificationBackgroundService(
ILogger<NotificationBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Processing scheduled notifications.");
await ProcessNotificationsAsync();
await Task.Delay(
TimeSpan.FromMinutes(5),
stoppingToken);
}
}
private Task ProcessNotificationsAsync()
{
throw new InvalidOperationException(
"Unable to process notifications.");
}
}The ProcessNotificationsAsync() method throws an exception.
Because there is no exception handling around the operation, the exception propagates out of ExecuteAsync().
The execution loop terminates immediately.
Starting with .NET 6, the default behavior of the Generic Host is to log an unhandled BackgroundService exception and stop the host.
This behavior is controlled by HostOptions.BackgroundServiceExceptionBehavior.
The default setting is:
BackgroundServiceExceptionBehavior.StopHostThis means an unhandled exception from a BackgroundService can cause the entire ASP.NET Core application to stop.
The behavior was changed in .NET 6 because earlier versions could leave the application running even though the background service had stopped working.
That created a difficult situation: the application appeared to be running, but the background operation was no longer executing.
The newer default behavior makes such failures more visible.
However, stopping the entire application might not be the desired behavior for every background job.
For example, if a notification fails because of a temporary database timeout, there may be no reason to stop the web application.
In this situation, the service should handle the job failure and continue processing.
Catch Exceptions Inside the Background Execution Loop
The first step toward making a BackgroundService more resilient is handling exceptions around individual operations.
Instead of allowing an exception to escape from ExecuteAsync(), catch it inside the execution loop.
Consider the following implementation:
public class NotificationBackgroundService : BackgroundService
{
private readonly ILogger<NotificationBackgroundService> _logger;
public NotificationBackgroundService(
ILogger<NotificationBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
_logger.LogInformation(
"Processing scheduled notifications.");
await ProcessNotificationsAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An error occurred while processing notifications.");
}
await Task.Delay(
TimeSpan.FromMinutes(5),
stoppingToken);
}
}
private Task ProcessNotificationsAsync(
CancellationToken cancellationToken)
{
// Notification processing logic.
return Task.CompletedTask;
}
}Now the behavior is different.
If ProcessNotificationsAsync() throws an exception, the catch block logs the error.
The exception does not escape from the execution loop, so the background service can continue.
After the delay, the next iteration starts.
The execution flow looks like this:
Background Service Starts
|
v
Start Processing
|
v
Did Job Succeed?
/ \
Yes No
| |
v v
Continue Log Error
| |
+-----+----+
|
v
Wait Interval
|
v
Process AgainThis is a simple but useful pattern for recurring background operations.
However, there is one important detail.
The exception handling should be placed around the individual operation, not used to hide every possible failure in the application.
For example, a database timeout during one job might be recoverable. A programming error caused by an invalid application state may require immediate attention.
Both should be logged, but they may need different recovery strategies.
Understand the Difference Between Job Failure and Service Failure
One of the most important design decisions is understanding what has actually failed.
A BackgroundService might execute hundreds or thousands of jobs during its lifetime.
If one job fails, it does not necessarily mean the entire background service should stop.
For example, imagine a worker responsible for sending notifications to users.
It processes three notifications:
Notification A is sent successfully.
Notification B fails because the email provider is temporarily unavailable.
Notification C is still waiting to be processed.
Should the entire worker stop because Notification B failed?
Usually, no.
The worker should record the failure, apply an appropriate retry strategy, and continue processing other notifications.
This means exception handling should happen at the job level whenever possible.
Consider this implementation:
private async Task ProcessNotificationsAsync(
IEnumerable<Notification> notifications,
CancellationToken cancellationToken)
{
foreach (var notification in notifications)
{
try
{
await SendNotificationAsync(
notification,
cancellationToken);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Failed to send notification {NotificationId}",
notification.Id);
}
}
}Here, a failure while sending one notification does not prevent the worker from attempting the next notification.
This is useful when jobs are independent of each other.
However, there are situations where processing must stop.
For example, if a financial transaction requires several dependent operations, continuing after an intermediate operation fails might leave the system in an inconsistent state.
The recovery strategy should depend on the business operation.
A useful rule is:
If an individual job fails independently, handle the failure at the job level.
If a complete batch must succeed or fail together, handle the batch as a unit.
If the worker itself cannot continue safely, allow the service to fail and rely on an appropriate recovery mechanism.
Do not treat every exception as a reason to continue.
Use PeriodicTimer for Recurring Background Operations
Many background services execute operations at regular intervals.
A common implementation uses Task.Delay() inside a while loop.
This works, but .NET also provides PeriodicTimer, which offers a convenient way to execute recurring operations.
Consider the following implementation:
public class NotificationBackgroundService : BackgroundService
{
private readonly ILogger<NotificationBackgroundService> _logger;
public NotificationBackgroundService(
ILogger<NotificationBackgroundService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(
TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
_logger.LogInformation(
"Starting notification processing.");
await ProcessNotificationsAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Notification processing failed.");
}
}
}
private Task ProcessNotificationsAsync(
CancellationToken cancellationToken)
{
// Process pending notifications.
return Task.CompletedTask;
}
}PeriodicTimer provides a tick at the configured interval.
The worker waits for the next tick, executes the operation, and waits for another tick.
If the operation fails, the exception is logged, and the loop continues waiting for subsequent ticks.
There is an important difference between this approach and a fixed delay after each execution.
With PeriodicTimer, ticks follow the timer's schedule. If an operation takes longer than the interval, missed ticks are not queued up as separate executions. The timer allows only one consumer to wait for ticks at a time.
This is useful for recurring operations where overlapping executions are not required.
If the requirement is to wait five minutes after a job completes before starting the next one, Task.Delay() after processing may be a better fit.
Choose the approach based on the required scheduling behavior.
Create a Dependency Injection Scope for Each Background Job
There is another issue developers often encounter when implementing BackgroundService.
Hosted services are registered as long-lived services.
By default, AddHostedService() registers the hosted service as a singleton.
This means you should not directly inject scoped dependencies, such as a DbContext, into the BackgroundService constructor.
Consider the following implementation:
public class NotificationBackgroundService : BackgroundService
{
private readonly AppDbContext _dbContext;
public NotificationBackgroundService(
AppDbContext dbContext)
{
_dbContext = dbContext;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
// Background processing.
}
}Because AppDbContext is normally registered as scoped, injecting it directly into a singleton hosted service creates a lifetime mismatch.
It can also lead to problems with long-lived DbContext instances, including accumulated tracked entities and unexpected state.
The recommended approach is to inject IServiceScopeFactory and create a new scope for each execution.
For example:
public class NotificationBackgroundService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<NotificationBackgroundService> _logger;
public NotificationBackgroundService(
IServiceScopeFactory scopeFactory,
ILogger<NotificationBackgroundService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(
TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await ProcessNotificationsAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Notification processing failed.");
}
}
}
private async Task ProcessNotificationsAsync(
CancellationToken cancellationToken)
{
await using var scope = _scopeFactory.CreateAsyncScope();
var notificationService = scope.ServiceProvider
.GetRequiredService<INotificationService>();
await notificationService.ProcessPendingAsync(
cancellationToken);
}
}Register the application services:
builder.Services.AddScoped<INotificationService, NotificationService>();
builder.Services.AddHostedService<NotificationBackgroundService>();Now each processing execution receives a new dependency injection scope.
The scoped services and DbContext instances are disposed when the scope is disposed.
This approach is particularly useful when background services interact with databases through Entity Framework Core.
It also keeps the background worker responsible for scheduling and lifecycle management while the actual business logic remains inside application services.
Add Retry Logic for Temporary Failures
Logging an exception and continuing with the next scheduled execution is useful, but it does not solve every problem.
Some failures are temporary.
For example:
Database connections may temporarily become unavailable.
An external API may return HTTP 503.
A network request may time out.
A message broker may temporarily reject a connection.
In these situations, retrying the operation may allow it to complete successfully without waiting for the next scheduled execution.
However, retries should be implemented carefully.
Retrying immediately without any delay can make the problem worse.
For example, if a database is already overloaded, repeatedly sending the same request can increase its load.
Join the conversation! Your thoughts help the community grow.