Introduction
Not every task in a web application needs to be completed while an HTTP request is being processed. Some operations take considerable time, run repeatedly, or need to execute independently of user activity. Examples include sending email notifications, generating reports, importing large files, cleaning up expired records, processing uploaded documents, and synchronizing data with external systems.
Performing these operations directly inside an API request can create several problems. A user may need to wait until the entire operation finishes, the request may time out, and the application may consume resources for longer than necessary. If a client disconnects while the operation is running, the application may also need to decide whether the work should continue or stop.
ASP.NET Core provides hosted services to run background tasks inside the application process. The framework includes IHostedService and BackgroundService, which allow developers to execute work independently of incoming HTTP requests while still using the application's dependency injection container, configuration, logging, and application lifecycle.
However, moving code into a background service does not automatically make it reliable. Developers must also consider dependency lifetimes, cancellation, exception handling, retries, application restarts, duplicate processing, and monitoring.
In this article, we will explore how to build background jobs in ASP.NET Core using hosted services, how to process queued work, and what additional considerations are required before using this approach in a production application.
Why Do We Need Background Jobs?
Consider an e-commerce application where a customer places an order. After saving the order, the application needs to send an email confirmation, generate an invoice, update reporting data, and notify another system.
If all these operations run inside the order creation API, the response may take several seconds. The customer does not necessarily need to wait for every operation to finish before receiving confirmation that the order has been accepted.
A better approach is to separate the main business operation from secondary tasks.
The API can validate the request, save the order, and return a response. Additional work can then be processed by background services.
Background jobs are useful for operations such as:
Sending email and push notifications.
Generating PDF invoices and reports.
Processing uploaded files.
Importing data from external systems.
Removing expired records.
Synchronizing information between applications.
Processing scheduled tasks.
Performing periodic database maintenance.
The important point is that background processing should be used when work does not need to be completed as part of the current HTTP response.
For example, saving an order is usually part of the main request because the application must confirm whether the order was successfully created. Sending a confirmation email can often happen afterward because it is a separate operation.
This separation can improve API response times and make the application easier to maintain. However, it also introduces a responsibility: the application must manage the background work correctly so that failures do not silently result in lost business operations.
Understanding Hosted Services in ASP.NET Core
ASP.NET Core provides two main interfaces for implementing hosted services.
IHostedService
IHostedService is the basic interface for services that run when the application starts and stop when the application shuts down.
It contains two methods:
StartAsync: Called when the application starts and the hosted service is being started.
StopAsync: Called when the application is shutting down and the service is being stopped.
A basic implementation looks like this:
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class ApplicationHostedService : IHostedService
{
private readonly ILogger<ApplicationHostedService> _logger;
public ApplicationHostedService(
ILogger<ApplicationHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Application hosted service started.");
return Task.CompletedTask;
}
public Task StopAsync(
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Application hosted service is stopping.");
return Task.CompletedTask;
}
}Register the service in Program.cs:
builder.Services.AddHostedService<ApplicationHostedService>();This implementation is useful when the service needs to perform startup or shutdown activities. However, IHostedService does not automatically provide a convenient method for writing a continuously running asynchronous loop.
Developers can implement their own task management using this interface, but they must carefully manage task execution, cancellation, and shutdown behavior.
BackgroundService
BackgroundService is an abstract class provided by Microsoft.Extensions.Hosting. It implements IHostedService and provides a simpler way to create long-running background operations.
It includes an abstract ExecuteAsync method. Developers implement this method to define the work performed by the background service.
For most continuously running background workers, BackgroundService is the more convenient option.
Consider the following example:
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class NotificationWorker : BackgroundService
{
private readonly ILogger<NotificationWorker> _logger;
public NotificationWorker(
ILogger<NotificationWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Background worker is running.");
await Task.Delay(
TimeSpan.FromSeconds(10),
stoppingToken);
}
}
}Register the worker:
builder.Services.AddHostedService<NotificationWorker>();When the application starts, the hosted service begins executing. The while loop continues until the application requests the service to stop.
The stoppingToken is important because it allows the application to communicate that the background service should stop. Passing this token to Task.Delay ensures that the delay can be interrupted during application shutdown instead of forcing the service to wait for the complete delay period.
A background service should not run an endless loop without observing cancellation. Otherwise, the application may have difficulty shutting down cleanly.
Understanding the Background Service Lifecycle
A hosted service is managed by the application's hosting infrastructure. It is not started independently of the application.
When ASP.NET Core starts, the hosting infrastructure starts the registered hosted services. When the application shuts down, it requests that the services stop and provides a cancellation token that should be observed by their ongoing operations.
This lifecycle is important for production applications because background work must cooperate with application startup and shutdown.
For example, suppose a worker is processing a large report when the application receives a shutdown request. The worker should stop accepting new work, observe cancellation where possible, and finish or safely interrupt the current operation according to the application's requirements.
The hosting infrastructure waits for hosted services to stop within the configured shutdown period. If a service ignores cancellation or performs an operation that cannot be interrupted, shutdown may take longer than expected.
There is also an important difference between application shutdown and business-level job completion. The application stopping does not automatically guarantee that an unfinished job will be completed later. If the job exists only in application memory, it may be lost when the process terminates.
For important work, the application needs a durable storage or messaging strategy rather than relying only on the lifetime of an in-memory background service.
Creating a Background Worker for Email Notifications
Let's build a simple example in which an ASP.NET Core application processes email notification requests in the background.
First, define a model representing the notification request.
public class EmailNotification
{
public string To { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
}Next, create an email service that performs the actual email operation.
public interface IEmailService
{
Task SendEmailAsync(
EmailNotification notification,
CancellationToken cancellationToken);
}A production implementation might use an email provider or an SMTP service. For this example, we will focus on how the background worker uses the service.
using Microsoft.Extensions.Logging;
public class EmailService : IEmailService
{
private readonly ILogger<EmailService> _logger;
public EmailService(
ILogger<EmailService> logger)
{
_logger = logger;
}
public async Task SendEmailAsync(
EmailNotification notification,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Replace this delay with an actual email provider call.
await Task.Delay(
TimeSpan.FromSeconds(2),
cancellationToken);
_logger.LogInformation(
"Email sent to {Recipient} with subject {Subject}",
notification.To,
notification.Subject);
}
}The example uses a delay to represent an external email operation. In a real application, this method would communicate with an email provider and should pass the cancellation token to the provider's asynchronous API whenever that API supports cancellation.
Now, create a background worker that processes notifications periodically.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class EmailNotificationWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<EmailNotificationWorker> _logger;
public EmailNotificationWorker(
IServiceScopeFactory scopeFactory,
ILogger<EmailNotificationWorker> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _scopeFactory.CreateScope();
var emailService = scope.ServiceProvider
.GetRequiredService<IEmailService>();
var notification = new EmailNotification
{
To = "[email protected]",
Subject = "Order Confirmation",
Message = "Your order has been placed successfully."
};
await emailService.SendEmailAsync(
notification,
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An error occurred while processing email notification.");
}
try
{
await Task.Delay(
TimeSpan.FromSeconds(30),
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
}
}
}Register the services:
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddHostedService<EmailNotificationWorker>();This example demonstrates the basic lifecycle of a background worker and shows how it can resolve a scoped service.
However, the notification is created directly inside the worker. This is suitable only for demonstrating the execution pattern. A real notification system should receive work from a queue or retrieve pending notifications from a database. Otherwise, the worker has no way to process different notifications submitted by users.
The next sections explain how to manage dependencies and queue work correctly.
Managing Scoped Dependencies in Background Services
One of the most common mistakes when implementing hosted services is injecting a scoped dependency directly into the background worker.
For example, consider an application that uses Entity Framework Core:
public class ReportWorker : BackgroundService
{
private readonly AppDbContext _dbContext;
public ReportWorker(AppDbContext dbContext)
{
_dbContext = dbContext;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
// Process reports.
}
}This implementation creates a dependency lifetime problem.
A hosted service is registered as a singleton by the hosting infrastructure. However, DbContext is normally registered as a scoped service through AddDbContext. A scoped service should be resolved within a valid dependency injection scope.
Injecting a scoped DbContext directly into a singleton hosted service can cause a lifetime validation error. Even if lifetime validation is disabled, using one DbContext for the entire lifetime of a background worker is not a good design.
DbContext is designed for a short unit of work. It is not thread-safe, and long-lived instances can retain tracked entities and stale state.
The recommended approach is to inject IServiceScopeFactory and create a scope for each unit of work.
public class ReportWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<ReportWorker> _logger;
public ReportWorker(
IServiceScopeFactory scopeFactory,
ILogger<ReportWorker> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
var pendingReports = await dbContext.Reports
.Where(x => x.Status == "Pending")
.ToListAsync(stoppingToken);
foreach (var report in pendingReports)
{
report.Status = "Processing";
}
await dbContext.SaveChangesAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Report processing failed.");
}
await Task.Delay(
TimeSpan.FromMinutes(1),
stoppingToken);
}
}
}In this example, a new dependency injection scope is created for each iteration. The DbContext is resolved from that scope and disposed when the iteration finishes.
For a production report processor, simply changing the status to Processing is not enough. The application also needs a strategy for handling reports that remain in Processing after a crash. This can involve a processing timestamp, a lease expiration time, or a recovery process that identifies abandoned jobs.
The important principle is to keep the lifetime of scoped dependencies aligned with the unit of work being processed.
Building a Background Task Queue With Channel
A background worker becomes more useful when other parts of the application can submit work for it to process.
ASP.NET Core applications can use System.Threading.Channels to implement an asynchronous producer-consumer queue.
A producer adds work to the queue, and a consumer reads and processes that work. The producer does not need to know how the consumer performs the operation.
A bounded channel is especially useful because it limits the number of items waiting in memory. Without a capacity limit, a large number of incoming requests could continuously add work until the application consumes too much memory.
Creating the Queue Model
First, define the interface for the background task queue.
public interface IBackgroundTaskQueue
{
ValueTask QueueBackgroundWorkItemAsync(
EmailNotification notification,
CancellationToken cancellationToken);
ValueTask<EmailNotification> DequeueAsync(
CancellationToken cancellationToken);
}This interface provides two operations. QueueBackgroundWorkItemAsync adds a notification to the queue, while DequeueAsync waits until a notification is available.
Implementing a Bounded Channel
Now, create the queue implementation.
using System.Threading.Channels;
public class BackgroundTaskQueue : IBackgroundTaskQueue
{
private readonly Channel<EmailNotification> _queue;
public BackgroundTaskQueue(int capacity)
{
var options = new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
};
_queue = Channel.CreateBounded<EmailNotification>(
options);
}
public async ValueTask QueueBackgroundWorkItemAsync(
EmailNotification notification,
CancellationToken cancellationToken)
{
await _queue.Writer.WriteAsync(
notification,
cancellationToken);
}
public async ValueTask<EmailNotification> DequeueAsync(
CancellationToken cancellationToken)
{
return await _queue.Reader.ReadAsync(
cancellationToken);
}
}The channel is created with a fixed capacity. In this example, the application can hold a maximum of 100 pending notifications in the queue.
The FullMode property is set to Wait. When the queue reaches its capacity, a new producer must wait until the consumer removes an item and makes room. This behavior is called backpressure.
Backpressure prevents the application from accepting unlimited work into memory. However, it also means that an API submitting work may wait when the queue is full. The application should decide how long it is willing to wait and what response it should return when capacity is unavailable.
SingleReader is set to true because this example uses one worker to read from the channel. SingleWriter is false because multiple API requests may submit notifications at the same time.
These settings describe the expected usage pattern and can help the channel implementation optimize its internal behavior. They should match the actual number of readers and writers used by the application.
Creating the Queue Worker
The worker continuously reads notifications and processes them.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public class EmailQueueWorker : BackgroundService
{
private readonly IBackgroundTaskQueue _queue;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<EmailQueueWorker> _logger;
public EmailQueueWorker(
IBackgroundTaskQueue queue,
IServiceScopeFactory scopeFactory,
ILogger<EmailQueueWorker> logger)
{
_queue = queue;
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
EmailNotification notification;
try
{
notification = await _queue.DequeueAsync(
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
try
{
using var scope = _scopeFactory.CreateScope();
var emailService = scope.ServiceProvider
.GetRequiredService<IEmailService>();
await emailService.SendEmailAsync(
notification,
stoppingToken);
_logger.LogInformation(
"Notification processed for {Recipient}",
notification.To);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Failed to process notification for {Recipient}",
notification.To);
}
}
}
}
Join the conversation! Your thoughts help the community grow.