In ASP.NET Core, how do you hand work from an endpoint to a background consumer using a System.Threading.Channels Channel<T>?
answer
- one queue shared by the whole process
- Writer for producers, Reader for consumers
- WriteAsync, then 202 Accepted
- await foreach over ReadAllAsync(stoppingToken)
- ends when Writer.Complete() is called
basics
~10 sRegister one Channel<T> as a singleton. The endpoint writes a job with channel.Writer.WriteAsync and returns 202 Accepted; a BackgroundService reads jobs one by one with await foreach over channel.Reader.ReadAllAsync(stoppingToken).
solid answer
~40 sA `Channel<T>` from `System.Threading.Channels` is an in-memory, thread-safe producer/consumer queue with two halves: `Writer` (`ChannelWriter<T>`) and `Reader` (`ChannelReader<T>`). Create it once, for example `Channel.CreateBounded<ThumbnailJob>(500)`, and register it as a **singleton** so the endpoints and the consumer share one queue. The upload endpoint calls `await channel.Writer.WriteAsync(job, ct)` and returns `202 Accepted`. A hosted `BackgroundService` runs `await foreach (var job in channel.Reader.ReadAllAsync(stoppingToken))`: the loop waits without blocking a thread while the channel is empty, yields items in the order written, and ends once the writer calls `Complete()` and the remaining items are read. ASP.NET Core ships no queue type of its own; the docs' `IBackgroundTaskQueue` is sample code built on a channel.
code
csharp · 24 linesusing System.Threading.Channels;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(Channel.CreateBounded<ThumbnailJob>(500));
builder.Services.AddHostedService<ThumbnailWorker>();
var app = builder.Build();
app.MapPost("/photos/{id:guid}/thumbnails", async (Guid id, Channel<ThumbnailJob> queue, CancellationToken ct) =>
{
await queue.Writer.WriteAsync(new ThumbnailJob(id), ct);
return TypedResults.Accepted($"/photos/{id}");
});
app.Run();
public sealed record ThumbnailJob(Guid PhotoId);
public sealed class ThumbnailWorker(Channel<ThumbnailJob> queue, ThumbnailRenderer renderer) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var job in queue.Reader.ReadAllAsync(stoppingToken))
await renderer.RenderAsync(job.PhotoId, stoppingToken);
}
}go deeper
Recall the shape: a singleton Channel<T>, Writer.WriteAsync in the endpoint, and await foreach over Reader.ReadAllAsync in a BackgroundService.
Explain how ReadAllAsync waits, yields and ends, why the channel must be a singleton, and why jobs carry ids rather than request objects.
Point out the limits up front: in-memory only, per process, lost on restart, and decide whether the work can tolerate that before choosing a channel.
Frame when an in-process queue is an acceptable trade for simplicity, and what signals mean the system needs a durable queue instead.
## The problem a channel solves On a photo-sharing site, a user uploads a picture and the app must render three thumbnail sizes. Rendering takes seconds of CPU, and the user should not wait for it. The endpoint needs to **hand the job off** to something that runs outside the request, inside the same process. ASP.NET Core does not ship a work-queue type; the building block is `System.Threading.Channels`, part of .NET. ## The pieces | Type | Role | Members you use | |---|---|---| | `Channel<T>` | the queue; holds both halves | `Writer`, `Reader` | | `ChannelWriter<T>` | producer side | `WriteAsync`, `TryWrite`, `Complete`, `TryComplete` | | `ChannelReader<T>` | consumer side | `ReadAllAsync`, `ReadAsync`, `TryRead`, `WaitToReadAsync` | | `Channel` (static) | factory | `CreateBounded<T>`, `CreateUnbounded<T>` | A channel is thread-safe: any number of concurrent requests can write while a consumer reads. ## Wiring it in Program.cs 1. Create the channel once and register it with `builder.Services.AddSingleton(...)`. Some teams register only `ChannelWriter<T>` for endpoints and `ChannelReader<T>` for the consumer, so neither side can misuse the other half. 2. Register the consumer with `builder.Services.AddHostedService<ThumbnailWorker>()`. 3. In the endpoint, inject the channel, write the job and return `TypedResults.Accepted(...)`: the request is acknowledged, the work is pending. 4. In the consumer's `ExecuteAsync`, loop with `await foreach` over `ReadAllAsync(stoppingToken)`. The job should be a small, self-contained message, such as a record holding the photo id. It should not carry the request's `HttpContext` or a scoped `DbContext`: those belong to a request that will be over by the time the job runs. The consumer creates its own scope for each job. ## How ReadAllAsync behaves `ReadAllAsync` returns an `IAsyncEnumerable<T>`. Under the hood it loops on `WaitToReadAsync` and drains with `TryRead`: - **Empty but open:** the enumeration waits asynchronously; no thread is blocked. - **Items present:** they are yielded first in, first out. - **Completed with `Complete()` and drained:** `MoveNextAsync` returns `false` and the `await foreach` ends normally. - **Completed with `Complete(exception)`:** after the remaining items, the enumeration throws that exception. - **Token cancelled:** the enumeration throws `OperationCanceledException`, which at shutdown is the normal way out of `ExecuteAsync`. ## Why a singleton The whole design rests on producer and consumer holding the **same** instance. Registered as scoped, each request would get its own channel that no consumer ever reads; registered as transient, every injection would create a new, empty channel. The jobs would vanish without an error. ## Common mistakes - **Creating the channel inside the endpoint** or in a scoped service: each request then writes to a queue nobody reads. - **Forgetting to register the consumer** with `AddHostedService`: writes succeed until a bounded channel fills, then every upload waits. - **Reading with a `while (true)` and `ReadAsync`** without handling `ChannelClosedException`: `ReadAllAsync` already ends cleanly on completion. - **Doing the heavy work in the endpoint anyway** and queueing only a notification: the request is no faster. ## What it is not - **Not durable.** Items live in process memory; a restart or crash loses whatever is queued. - **Not shared across replicas.** Each process has its own channel; a job written on instance A is read only on instance A. - **Not a framework API surface.** ASP.NET Core has no `QueueBackgroundWorkItem`; `HostingEnvironment.QueueBackgroundWorkItem` belongs to ASP.NET 4.x (`System.Web`), and the hosted-services docs build an `IBackgroundTaskQueue` sample on top of a bounded channel. Those limits are why a channel suits work that may be redone or dropped, and why the queue's capacity, shutdown behaviour and durability are the follow-up questions.
- Why might you register ChannelWriter<T> and ChannelReader<T> separately instead of Channel<T>?It narrows each side's power: endpoints get only `ChannelWriter<T>` and cannot read or steal jobs, and the consumer gets only `ChannelReader<T>`. Register the channel instance once, then add `ChannelWriter<T>` and `ChannelReader<T>` singletons whose factories return `channel.Writer` and `channel.Reader` of that same instance.
- What should a queued job carry, and what should it never carry?A small message with identifiers and values, such as the photo id and the sizes to render. Never the request's `HttpContext`, a scoped `DbContext` or other request-bound objects: the request ends, its scope is disposed, and the consumer would touch dead objects. The consumer reloads what it needs inside its own scope.
- Register the Channel<T> as scoped so each request gets a clean queue
- ASP.NET Core provides HostingEnvironment.QueueBackgroundWorkItem for this
- IBackgroundTaskQueue is a framework interface ASP.NET Core registers for you
- ReadAllAsync ends as soon as the channel is momentarily empty
- A Channel<T> keeps queued items across an app restart