Introduction
The primary responsibility of a Web API endpoint is usually to receive a request, validate it, start the required operation, and return a response within a reasonable amount of time. However, operations such as report generation, large-scale data processing, email delivery, file creation, and notification delivery can take considerably longer. Running these operations directly inside an HTTP request increases response times and reduces application reliability.
In this lesson, we will first examine why long-running work should be separated from the request-response cycle. We will then use ASP.NET Core's IHostedService and BackgroundService abstractions to create a small and safe in-process task queue. We will build an API endpoint that enqueues work, a worker that consumes it, and a sample report service.
This approach does not replace RabbitMQ, which will be introduced later in the course. An in-process queue exists only inside the current process. If the application stops, pending in-memory work can be lost. Even so, it is an important first step for understanding background processing and task lifecycles.
Why should long-running work be separated from HTTP requests?
Generating a report by reading thousands of records, calculating values for each record, and creating a file may appear straightforward inside an endpoint. In practice, this design creates several problems:
- Long response times: The client must keep the connection open until the report is complete.
- Timeout risk: A reverse proxy, load balancer, or client may close the connection after a configured timeout.
- Higher resource consumption: Each long-running request consumes an HTTP connection, thread pool resources, and often a database connection.
- Duplicate submissions: If the client receives a timeout and retries, the same report may be generated twice.
- Harder scaling: The API server must handle both fast requests and resource-intensive work.
- Poor user experience: The client cannot easily track progress or retrieve the final result.
For these reasons, an endpoint should often enqueue the work and return 202 Accepted. The response can include a job identifier. The client can then query the job status or receive a notification when the work is complete.
An unsuitable approach
[HttpPost("reports")]
public async Task<IActionResult> CreateReport(CancellationToken cancellationToken)
{
var report = await _reportService.GenerateAsync(cancellationToken);
await _emailService.SendAsync(report, cancellationToken);
return Ok(new { report.FileName });
}This code can work technically, but the HTTP response is not returned until both the report and the email operation finish. In addition, cancellation of the client request may cancel the work as well. Some workflows require the operation to continue after the client disconnects, so this relationship must be designed explicitly.
A more appropriate flow
- The endpoint validates the request and authorization.
- It creates a job identifier.
- It enqueues the work item.
- It returns
202 Acceptedwith the job identifier. - The worker executes the job in the background.
- The job status is stored in a database or another durable store.
IHostedService and BackgroundService
IHostedService defines StartAsync and StopAsync for services managed by the application host. A hosted service is activated while the ASP.NET Core application starts and is stopped in a controlled manner when the application shuts down.
BackgroundService is a base class for long-running hosted services. In most cases, we override ExecuteAsync(CancellationToken). The task returned by this method represents the lifetime of the background service. When the host shuts down, the cancellation token is signaled and the worker is expected to exit quickly and in a controlled way.
Long-running loops should be placed in ExecuteAsync rather than StartAsync. Startup operations should remain short; otherwise, starting other hosted services can be delayed.
Designing an in-process task queue
We will use the .NET System.Threading.Channels library for the task queue. A Channel provides asynchronous data transfer between one or more producers and consumers. It is important to configure the channel with a bounded capacity. This prevents memory usage from growing without limit when producers are faster than consumers.
1. Queue contract
using System.Threading.Channels;
public interface IBackgroundTaskQueue
{
ValueTask QueueAsync(
Func<CancellationToken, ValueTask> workItem,
CancellationToken cancellationToken = default);
ValueTask<Func<CancellationToken, ValueTask>> DequeueAsync(
CancellationToken cancellationToken);
}The work item is represented by a function that receives a cancellation token. This allows a running operation to observe the cancellation signal when the worker is stopping.
2. Bounded channel implementation
using System.Threading.Channels;
public sealed class BackgroundTaskQueue : IBackgroundTaskQueue
{
private readonly Channel<Func<CancellationToken, ValueTask>> _queue;
public BackgroundTaskQueue(int capacity)
{
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
_queue = Channel.CreateBounded<Func<CancellationToken, ValueTask>>(
new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
}
public ValueTask QueueAsync(
Func<CancellationToken, ValueTask> workItem,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(workItem);
return _queue.Writer.WriteAsync(workItem, cancellationToken);
}
public ValueTask<Func<CancellationToken, ValueTask>> DequeueAsync(
CancellationToken cancellationToken)
{
return _queue.Reader.ReadAsync(cancellationToken);
}
}BoundedChannelFullMode.Wait makes the producer wait when the queue is full. This creates backpressure. Other modes, such as DropWrite or DropOldest, may be appropriate for some telemetry scenarios, but they must be evaluated carefully for work that must not be lost, such as reports or emails.
3. Creating the worker
public sealed class QueuedBackgroundService : BackgroundService
{
private readonly IBackgroundTaskQueue _taskQueue;
private readonly ILogger<QueuedBackgroundService> _logger;
public QueuedBackgroundService(
IBackgroundTaskQueue taskQueue,
ILogger<QueuedBackgroundService> logger)
{
_taskQueue = taskQueue;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Background worker started.");
while (!stoppingToken.IsCancellationRequested)
{
Func<CancellationToken, ValueTask> workItem;
try
{
workItem = await _taskQueue.DequeueAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
try
{
await workItem(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Background work was cancelled.");
}
catch (Exception exception)
{
_logger.LogError(exception, "Background work failed.");
}
}
_logger.LogInformation("Background worker stopped.");
}
}The worker awaits each work item individually. It is important to catch exceptions for each item; otherwise, one failed task can terminate the entire worker. In a production system, the exception should be logged, the job should be marked as failed, and retry behavior should be added later.
4. Registering services with dependency injection
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IBackgroundTaskQueue>(_ =>
new BackgroundTaskQueue(capacity: 100));
builder.Services.AddHostedService<QueuedBackgroundService>();
builder.Services.AddScoped<IReportService, ReportService>();
var app = builder.Build();The queue should be a singleton because the endpoint and the worker must share the same queue. The hosted service is also managed as a singleton by the host. Therefore, scoped services must not be injected directly into the worker's constructor.
Using scoped services safely
Services such as Entity Framework Core's DbContext usually have a scoped lifetime. Because the worker is a singleton, create a new scope for each work item by using IServiceScopeFactory.
public sealed class ReportWorker
{
private readonly IServiceScopeFactory _scopeFactory;
public ReportWorker(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public async ValueTask ExecuteAsync(
Guid jobId,
CancellationToken cancellationToken)
{
await using var scope = _scopeFactory.CreateAsyncScope();
var reportService = scope.ServiceProvider
.GetRequiredService<IReportService>();
await reportService.GenerateAsync(jobId, cancellationToken);
}
}Creating a scope per job ensures that the DbContext and other scoped dependencies are created and disposed at the correct time. Keeping one DbContext alive inside a long-running worker can cause state, memory, and thread-safety problems.
Enqueuing work from an endpoint
Let us create an endpoint that sends a report job to the queue. The example uses a Guid so the job can be followed in logs.
app.MapPost("/reports", async (
IBackgroundTaskQueue taskQueue,
ReportWorker reportWorker,
CancellationToken requestToken) =>
{
var jobId = Guid.NewGuid();
await taskQueue.QueueAsync(
token => reportWorker.ExecuteAsync(jobId, token),
requestToken);
return Results.Accepted($"/reports/{jobId}", new
{
JobId = jobId,
Status = "Queued"
});
});In this example, the request token is used only while the work is being added to the queue. After the work is enqueued, the worker uses its own stoppingToken. With this design, a client disconnect does not automatically cancel work that has already been accepted.
In a production system, job status should be stored in a durable database such as SQL Server rather than only in memory. Possible states include Queued, Processing, Completed, Failed, and Cancelled. This allows the client to monitor progress through a separate status endpoint.
Cancellation and graceful shutdown
When an application is stopped normally, the host asks hosted services to stop and signals their cancellation tokens. The worker should observe this token. Pending ReadAsync calls and active Task.Delay, database, or HTTP operations should also receive the token whenever they support cancellation.
Graceful shutdown does not mean that every operation will always finish. The shutdown period is limited. Critical work should therefore be designed to save a safe intermediate state, remain retryable, and be idempotent. If the process crashes unexpectedly, StopAsync may not be called, and all pending in-memory work can be lost. This is a fundamental difference between an in-process queue and durable solutions such as RabbitMQ or Hangfire.
Example of cancellation-aware work
public async ValueTask GenerateAsync(
Guid jobId,
CancellationToken cancellationToken)
{
for (var page = 1; page <= 10; page++)
{
cancellationToken.ThrowIfCancellationRequested();
await ProcessPageAsync(page, cancellationToken);
}
}
private static async Task ProcessPageAsync(
int page,
CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken);
}Checking the token only at the beginning of a loop may not be sufficient. The token should also be passed to long-running operations. An OperationCanceledException can be an expected result during normal shutdown and should not automatically be reported as a system failure.
Common mistakes
- Using fire-and-forget tasks: Starting
_ = Task.Run(...)inside an endpoint can hide exceptions, use disposed scoped services, and lose work during application shutdown. - Creating an unbounded queue: Memory usage can grow without control when traffic increases. Prefer a bounded channel and backpressure.
- Injecting scoped services directly into a singleton worker: Create a new scope for each work item.
- Ignoring CancellationToken: The worker may take too long to stop and fail to shut down gracefully.
- Not persisting jobs: Pending jobs in an in-process queue disappear when the process stops.
- Allowing one failure to stop the worker: Execute each work item inside its own try-catch block.
- Coupling job lifetime to the client request: Once accepted, a job's lifecycle should usually be independent of the HTTP request.
Practice exercise
Build the following small application:
- Set the
BackgroundTaskQueuecapacity to 3. - Create a
POST /notificationsendpoint that enqueues a notification. - Simulate a two-second delay for each notification in the worker.
- Write logs for job start, completion, cancellation, and failure.
- Stop the application after submitting a job and observe the cancellation logs.
- Submit more than three concurrent jobs and verify that producers wait when the queue is full.
- Design a job status model that could later be persisted in a database.
As a second step, try running two consumers instead of one. Consider how to prevent the same job from being executed twice. This question prepares you for idempotency and distributed message processing, which will be covered in later lessons.
Conclusion
Moving long-running operations out of HTTP requests makes API response times and resource usage more predictable. IHostedService integrates background work with the host lifecycle, while BackgroundService simplifies the implementation of long-running workers. A bounded Channel-based queue separates producers from consumers and provides backpressure.
The solution built in this lesson is an in-process starting architecture. Production systems may also need durable jobs, coordination across multiple application instances, retries, dead-letter behavior, and reliable recovery after restarts. Those requirements lead naturally to the RabbitMQ concepts covered in the next lessons, including durable messaging, acknowledgements, and reliable consumer design.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=net-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/responses?view=aspnetcore-10.0