This post was originally published in Portuguese on my blog: Processando em segundo plano no .NET 8 com BackgroundService e Channel.
We've all been there: the endpoint receives a request, does something slow (generates a report, sends an email, calls a slow service) and the client sits waiting until it times out. The classic way out is to respond right away and do the work in the background. You can jump straight to a broker like RabbitMQ, but that's often overkill. In .NET 8 you already have what you need at home: BackgroundService and Channel<T>.
The idea
The API doesn't process anything. It registers the job, puts it in a queue and returns 202 Accepted with a Location header. On the other side, a BackgroundService loops reading from the queue and processing one job at a time. The client polls GET /jobs/{id} to get the status: Queued, Processing, Completed or Failed.
The project has three pieces: ChannelJobQueue (the queue), JobStore (a concurrent dictionary with the state of each job) and JobWorker (the consumer). Everything is in memory, on purpose, to keep the mechanism visible.
The queue
Channel.CreateBounded creates a channel with a fixed capacity, and that choice matters: without a limit, a burst of requests turns into uncontrolled memory growth. With a limit, you decide what happens when it fills up. In ChannelJobQueue, the TryEnqueue method uses TryWrite, which returns false immediately if there is no room, instead of holding the request waiting.
public sealed class ChannelJobQueue : IJobQueue { private readonly Channel<Job> _channel; public ChannelJobQueue(int capacity) { _channel = Channel.CreateBounded<Job>(new BoundedChannelOptions(capacity) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true }); } // Returns false immediately when the queue is full, instead of waiting. public bool TryEnqueue(Job job) => _channel.Writer.TryWrite(job); The endpoint
In POST /jobs the order matters: first store.Add, then TryEnqueue. If it were the other way around, the worker could pick up the job before it exists in the JobStore and try to update an unknown id. If the queue is full, I remove the job from the store and respond with 503 using Results.Problem. That's backpressure reaching the client: better to say "try again in a bit" than to accept what you can't handle.
var job = new Job(Guid.NewGuid(), request.Name); // Register the job before enqueueing, so the worker never sees an unknown id. store.Add(job); if (!queue.TryEnqueue(job)) { store.Remove(job.Id); return Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Queue is full."); } return Results.Accepted($"/jobs/{job.Id}", new { job.Id }); The worker
JobWorker inherits from BackgroundService and implements ExecuteAsync. The await foreach over DequeueAllAsync (which is ReadAllAsync on the channel underneath) sleeps when the queue is empty and wakes up when an item arrives, with no polling and no Task.Delay in a loop. When the host receives the stop signal, stoppingToken is cancelled, the enumerator throws OperationCanceledException and I just log the shutdown.
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { await foreach (var job in queue.DequeueAllAsync(stoppingToken)) { await ProcessAsync(job, stoppingToken); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { logger.LogInformation("Worker is shutting down."); } } The other thing to watch is failure. If an exception escapes the loop, ExecuteAsync ends and the worker dies silently: the API keeps accepting jobs that nobody processes anymore. That's why ProcessAsync catches the exception for each job, marks it as Failed and moves on to the next one. The when (ex is not OperationCanceledException) filter lets the shutdown cancellation through.
catch (Exception ex) when (ex is not OperationCanceledException) { // One bad job must not kill the worker loop. store.SetStatus(job.Id, JobStatus.Failed); logger.LogError(ex, "Job {JobId} failed.", job.Id); } Testing
The tests use WebApplicationFactory, one instance per test, since the queue and the store are in-memory singletons. Worker:DelayMs and Queue:Capacity are set through AddInMemoryCollection. The most interesting test is the full-queue one: with capacity 1 and the worker busy for 3 seconds, the first job becomes Processing, the second takes the queue slot and the third gets a 503. Waiting for the Processing status before sending the second one avoids a race between the test and the worker.
await using var factory = CreateFactory(delayMs: 3000, capacity: 1); var client = factory.CreateClient(); // The worker takes the first job and stays busy with it. var firstId = await CreateJobAsync(client, "first"); await WaitForStatusAsync(client, firstId, "Processing"); // The second job fills the queue (capacity 1). await CreateJobAsync(client, "second"); // The third one has no room left. var response = await client.PostAsJsonAsync("/jobs", new { name = "third" }); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); There are also tests for the 202, the 400, the 404, a job that completes, and a worker that survives a failing job (the name fail simulates the error).
Running with Docker
docker-compose.yml has the app service, which brings up the API on port 8080, and the tests service, which runs xUnit. With the API up, just create a job and check its status:
docker compose up --build curl -X POST http://localhost:8080/jobs -H "Content-Type: application/json" -d '{"name":"report"}' curl http://localhost:8080/jobs/<id> docker compose run --rm tests When this isn't enough
An in-memory queue doesn't survive a restart and doesn't share work across multiple instances. If the job can't be lost, or if you have more than one replica, the way to go is a broker (RabbitMQ, Azure Service Bus) or an outbox table. For short, loss-tolerant tasks, like notifications or cache warming, Channel does the job with very little code.
The full code is here: programero-csharp/2026-11-background-service-channel.


