In an ASP.NET Core SignalR hub, how do you stream items to a client with IAsyncEnumerable<T> or ChannelReader<T>, and how does client cancellation reach you?
answer
- return type makes it a stream
- async iterator with yield return
- CancellationToken parameter, streams only
- return the ChannelReader early
- upload streams: StreamBufferCapacity 10
basics
~20 sA SignalR hub method becomes a server-to-client stream when it returns IAsyncEnumerable<T>, ChannelReader<T> or a Task of either. Add a CancellationToken parameter: SignalR cancels it when the client disposes its subscription or disconnects, so the producer stops.
solid answer
~50 sThe return type decides it: a hub method returning `IAsyncEnumerable<T>`, `ChannelReader<T>`, `Task<IAsyncEnumerable<T>>` or `Task<ChannelReader<T>>` is a streaming method, and each item is sent as it is produced. The simplest form is an async iterator with `yield return`. Streaming methods, and only those, may declare a `CancellationToken` parameter that SignalR supplies itself; it is cancelled when the client ends the stream (disposing the JavaScript subscription or cancelling the .NET token) or the connection drops. With a channel, return the reader immediately, write from a background task, and complete the writer in `finally`, passing the exception to flow an error. Streams do not count against `MaximumParallelInvocationsPerClient`, and the hub and its DI scope stay alive until the stream ends. For uploads, a method parameter of `ChannelReader<T>` or `IAsyncEnumerable<T>` receives a client stream, buffered up to `StreamBufferCapacity` items, 10 by default.
code
csharp · 20 linesusing System.Runtime.CompilerServices;
using Microsoft.AspNetCore.SignalR;
public record AnswerTally(int QuestionId, int[] CountsByChoice);
public class QuizHub(TallyStore tallies) : Hub
{
// Streams one tally per second until the client disposes the subscription
// or the connection drops; both cancel the token.
public async IAsyncEnumerable<AnswerTally> WatchTally(
int questionId,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
yield return tallies.Snapshot(questionId);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}
}go deeper
Remember that returning IAsyncEnumerable<T> or ChannelReader<T> from a hub method turns it into a stream the client subscribes to.
Explain the async iterator form, the CancellationToken SignalR supplies to streams only, and the channel rules about returning early and completing the writer.
Reason about long-lived streams: hub and scope held open, no parallel-invocation limit, error flow through Complete(ex), and upload buffering with StreamBufferCapacity.
Decide when streaming over a hub beats repeated pushes or a separate endpoint, weighing per-connection resources held by many concurrent streams.
## Why stream through a hub A normal hub method returns one value when it completes. Some results arrive over time: in the live classroom quiz, the teacher wants the **answer tally** to update as students answer, for as long as the question is open. SignalR streaming sends each item the moment it exists, over the same connection, and lets either side stop early. ## Server-to-client: the return type decides SignalR treats a hub method as **streaming** when its return type is one of: - `IAsyncEnumerable<T>` - `ChannelReader<T>` - `Task<IAsyncEnumerable<T>>` - `Task<ChannelReader<T>>` The client must start it as a stream (`connection.stream(...)` in JavaScript, `StreamAsync<T>` or `StreamAsChannelAsync<T>` in .NET); a plain invoke of a streaming method is rejected. ### The async iterator form ```csharp public async IAsyncEnumerable<AnswerTally> WatchTally( int questionId, [EnumeratorCancellation] CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { yield return tallies.Snapshot(questionId); await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } } ``` This is the recommended form: no channel to complete, no early-return rule, and exceptions propagate naturally. ### The channel form ```csharp public ChannelReader<AnswerTally> WatchTallyChannel(int questionId, CancellationToken ct) { var channel = Channel.CreateBounded<AnswerTally>(10); _ = ProduceAsync(channel.Writer, questionId, ct); return channel.Reader; // return before producing } ``` Two rules come with channels: 1. **Return the reader as soon as possible** and write on a background task; the docs warn that other hub invocations are blocked until the reader is returned. 2. **Complete the writer in a `finally`**, calling `writer.Complete(ex)` with the caught exception to send an error to the client, or `Complete()` for a normal end. A writer that is never completed leaves the client waiting. ## How cancellation arrives A `CancellationToken` parameter is special only on streaming methods; SignalR removes it from the arguments the client sends and supplies its own token. That token is cancelled when: - the JavaScript client calls `dispose()` on the subscription returned by `subscribe`; - the .NET client cancels the token it passed to `StreamAsync` or `StreamAsChannelAsync`; - the connection closes. Use it to stop the producer and release resources. On an async iterator, `[EnumeratorCancellation]` also links the token passed to `GetAsyncEnumerator`. ## Lifetime and concurrency | Aspect | Normal hub method | Streaming hub method | |---|---|---| | Hub instance and DI scope | released when the method returns | kept until the stream completes | | `MaximumParallelInvocationsPerClient` (default 1) | applies | does not apply | | Can take a `CancellationToken` from SignalR | no | yes | Because streams are excluded from the per-client parallel limit, one client can open many concurrent streams. If that matters, the docs show wrapping the stream with your own per-connection counter. ## Client-to-server streaming The reverse direction is declared by parameters: a hub method taking a `ChannelReader<T>` or `IAsyncEnumerable<T>` receives items as the client writes them, for example a student's handwritten answer sent stroke by stroke. `HubOptions.StreamBufferCapacity` (default **10**) is the number of upload items buffered for such streams; when it is reached, processing of invocations is blocked until the server reads items. ## Under Native AOT .NET 9's AOT support for SignalR does not cover stream **parameters** whose item type is a value type, such as `ChannelReader<int>`; prefer reference-type items, such as a record, in AOT apps.
- Why does the ChannelReader form insist that you return the reader before producing items?SignalR can only start forwarding items once it has the reader, and the docs warn that other hub invocations are blocked until the `ChannelReader` is returned. Producing synchronously before returning would stall the stream and delay the connection's other calls. Start the producer on a background task, return the reader, and complete the writer in a `finally`.
- One teacher tab opens fifty tally streams; why does MaximumParallelInvocationsPerClient not stop it?That option limits only non-streaming invocations, default 1 per client. Streaming invocations are deliberately excluded because they are expected to be long-running and concurrent. To cap them, wrap the stream in your own per-connection counter that increments before yielding and decrements in a `finally`, as the SignalR docs show.
- A hub method returning Task<List<T>> streams the list items one by one.
- Any hub method can take a CancellationToken that fires when the client gives up.
- Returning a ChannelReader after filling it completely is the safe pattern.
- MaximumParallelInvocationsPerClient also caps how many streams a client can open.
- The hub instance is disposed as soon as a streaming method returns its enumerable.