skip to content

When a dashboard tab closes, how does an ASP.NET Core 10 SSE endpoint stop its IAsyncEnumerable, and why might the iterator keep running anyway?

level: seniorimportance: should knowfreq 33%

answer

  1. the token reaches the writes, maybe not you
  2. RequestAborted into SseFormatter.WriteAsync
  3. plain-T overloads wrap your sequence
  4. pass the handler's CancellationToken in
  5. finally in the iterator runs on dispose

basics

~20 s

ServerSentEventsResult passes RequestAborted to SseFormatter, which cancels its writes. Your iterator only stops waiting if the token reaches it: pass the handler's CancellationToken in explicitly, because the plain-T and string overloads enumerate your sequence without a token.

solid answer

~40 s

`ServerSentEventsResult<T>` calls `SseFormatter.WriteAsync(..., HttpContext.RequestAborted)`, which enumerates with `WithCancellation(token)` and passes the token to every write. Whether *your* iterator hears it depends on the overload. With `IAsyncEnumerable<SseItem<T>>` your sequence is enumerated directly, so a parameter marked `[EnumeratorCancellation]` receives the token. With `IAsyncEnumerable<T>` or `IAsyncEnumerable<string>`, the result wraps your sequence in its own iterator that enumerates it with no token, so the attribute alone never fires. An iterator awaiting the next build step then keeps running after the tab closes and stops only when it yields and the cancelled write fails. The safe pattern, which the docs samples use, is a `CancellationToken` parameter on the Minimal API handler (bound to `RequestAborted`) passed into the iterator. Put unsubscribe logic in a `finally` inside the iterator: it runs when the enumerator is disposed.

code

csharp · 17 lines
csharp
app.MapGet("/builds/{buildId}/events", (string buildId, BuildEventBus bus, CancellationToken ct) =>
    TypedResults.ServerSentEvents(Follow(bus, buildId, ct)));   // ct is RequestAborted

static async IAsyncEnumerable<BuildEvent> Follow(BuildEventBus bus, string buildId,
    [EnumeratorCancellation] CancellationToken ct = default)
{
    var subscription = bus.Subscribe(buildId);        // exposes a ChannelReader<BuildEvent>
    try
    {
        await foreach (var e in subscription.Reader.ReadAllAsync(ct))  // wakes on disconnect
            yield return e;
    }
    finally
    {
        bus.Unsubscribe(subscription);                // runs when the enumerator is disposed
    }
}

go deeper

for a junior

Know that a closed tab cancels HttpContext.RequestAborted and that a Minimal API CancellationToken parameter is that token.

for a middle

Explain how ServerSentEventsResult passes RequestAborted to SseFormatter and why the iterator must receive the token to stop waiting.

for a senior

Know that the plain-T overloads wrap your sequence without a token, pass the handler's token explicitly, move cleanup into the iterator's finally, and treat cancellation exceptions as normal.

for a principal

Account for abandoned streams in capacity plans and decide how idle connections are detected and reaped across intermediaries.

## How a disconnect is noticed When a browser tab showing a build closes, the TCP connection ends. The server notices and signals **`HttpContext.RequestAborted`**, the request's cancellation token. Everything that should stop has to be listening to that token. With `TypedResults.ServerSentEvents` the plumbing is: 1. `ServerSentEventsResult<T>.ExecuteAsync` calls `SseFormatter.WriteAsync(..., httpContext.Response.Body, ..., httpContext.RequestAborted)`. 2. `SseFormatter` enumerates with `source.WithCancellation(cancellationToken)` and passes the same token to each `destination.WriteAsync`. 3. When the token fires, a pending write is cancelled, and the token is offered to the enumerator of whatever sequence `SseFormatter` was given. ## The gap: which sequence receives the token `WithCancellation` does not cancel anything by itself; it hands the token to `GetAsyncEnumerator`. For a C# async iterator (`async IAsyncEnumerable<T>` with `yield return`), the compiler only connects that token to a parameter marked **`[EnumeratorCancellation]`**. The twist in ASP.NET Core 10 is what `SseFormatter` actually enumerates: - **`ServerSentEvents<T>(IAsyncEnumerable<SseItem<T>>)`** stores your sequence as is, so the formatter's token reaches your attributed parameter. - **`ServerSentEvents<T>(IAsyncEnumerable<T>, eventType)`** and the string overload wrap your sequence in a private iterator that turns each item into an `SseItem<T>`. That wrapper runs `await foreach` over your sequence **without a token**, so the formatter's token stops at the wrapper. | How the iterator gets its token | Stops promptly when the tab closes? | |---|---| | no token parameter at all | no: only when it next yields and the write fails | | `[EnumeratorCancellation]` only, plain `T` or string overload | no: the wrapper enumerates it without a token | | `[EnumeratorCancellation]` only, `SseItem<T>` overload | yes: the formatter's token flows in | | the handler's `CancellationToken` passed as an argument | yes, with every overload | The failure is easy to miss in testing. An iterator that yields every second stops within a second anyway, because the next write fails. An iterator that waits for the **next build event**, which may be forty minutes away for a queued build, holds its subscription, timers and perhaps a database connection for those forty minutes, per closed tab. Passing the handler's token explicitly, as the ASP.NET Core docs samples do, works whichever overload you call. ## Cleaning up Resources that belong to the stream belong **inside the iterator**: - subscribe at the top of the iterator; - `yield return` events inside a `try` block; - unsubscribe in the matching `finally`. When enumeration ends (completion, cancellation, a failed write), the `await foreach` that drives your sequence disposes its enumerator, and disposing a suspended async iterator runs its pending `finally` blocks. Code placed after `return TypedResults.ServerSentEvents(...)` in the handler is no help: the handler returns before streaming starts. ## Expected exceptions A disconnect typically ends the stream with an `OperationCanceledException` or an I/O exception from the write. That is the normal end of an SSE request, not a fault. Do not log it as an error, and do not try to write a farewell event: the client is gone. ## Hand-written streams The same rule applies to a hand-written loop: take the handler's `CancellationToken` (or `context.RequestAborted`) and pass it to every await inside the loop, including the wait for the next event. ## Detection limits `RequestAborted` fires when the server sees the connection close. If an intermediary keeps its upstream connection open after the browser leaves, the server cannot know; such streams end only when the intermediary gives up on them.

  • If the token is passed explicitly, is [EnumeratorCancellation] still worth adding?
    It does no harm and keeps the iterator correct if someone later enumerates it with `WithCancellation` directly, or switches the endpoint to the `SseItem<T>` overload; when both an argument and an enumerator token are present, the compiler combines them. But with the plain-`T` overload, the explicit argument is what actually stops the iterator.
  • Why not unsubscribe in the endpoint handler after returning the result?
    The handler only builds the result; `ExecuteAsync` streams after the handler has returned. Any code after the `return` never runs, and code before it runs before the first event. Ownership of the subscription has to move into the iterator, whose `finally` runs exactly when streaming ends.

  • TypedResults.ServerSentEvents disposes the subscription after the handler returns.
  • [EnumeratorCancellation] alone always receives RequestAborted, whichever ServerSentEvents overload is used.
  • The iterator stops instantly on disconnect even without a token, because the write fails.
  • Catch OperationCanceledException and send a final event to the departed client.
  • Unsubscribe after the return statement of the endpoint lambda.

Assumes ASP.NET Core 10, where ServerSentEventsResult<T> passes HttpContext.RequestAborted to SseFormatter.WriteAsync and wraps plain-T sequences in its own token-less iterator; on 8 and 9 the same token discipline applies to hand-written loops.