Recursive AI

Cancel a streaming chat response with CancellationToken in C#

OneLLM is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Pass a token to StreamAsync, then call Cancel(). Try it offline without an API key.

Terminal
dotnet add package RecursiveAI.OneLlm

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneLlm.Messages;
using OneLlm.Providers;
using OneLlm.Testing;
 
using var stop =
    new CancellationTokenSource();
var script = new ScriptedProvider().Enqueue(
    ScriptStep.Text(
        "First", "Second", "Third"));
var request = new ChatRequest
    { Model = "demo" };
var stream = script.StreamAsync(
    request, stop.Token);
int chunks = 0;
 
try
{
    await foreach (var part in stream)
    {
        if (part.Kind !=
            StreamEventKind.TextDelta)
            continue;
        Console.WriteLine(part.GetText());
        chunks++;
        stop.Cancel();
    }
    throw new InvalidOperationException(
        "Expected cancellation.");
}
catch (OperationCanceledException)
    when (stop.IsCancellationRequested)
{
    if (chunks != 1)
        throw new InvalidOperationException(
        "Expected one chunk.");
    Console.WriteLine(
        "Canceled after one chunk.");
}

Paste the code above into Program.cs of a new dotnet new console project and dotnet run, or unzip the example and dotnet run.

Text
First
Canceled after one chunk.

The loop counts text deltas, not stream-start or other events. The example fails if the loop completes normally or yields more text after Cancel().

Variations

Start with a canceled token. Add this just before the try block, then change the catch body to check that zero text chunks arrived:

C#
// Before try:
stop.Cancel();
 
// Inside the catch block:
if (chunks != 0)
    throw new InvalidOperationException("Expected no text.");
Console.WriteLine("Canceled before any text.");
Text
Canceled before any text.

Cancel through Runtime.StreamAsync. Pass the token to TextAsync when consuming a runtime’s text stream. This run uses a scripted stand-in, not a live service.

C#
using OneLlm;
using OneLlm.Catalog;
using OneLlm.Testing;
 
var layer = CatalogLayer.FromYaml(CatalogLayer.User, """
    name: local
    models:
      - name: demo-chat
        contextWindow: 4096
    """);
var runtime = new Runtime { Catalog = ModelCatalog.Create([layer]) };
runtime.Providers.Set("local", new ScriptedProvider("local")
    .Enqueue(ScriptStep.Text("First", "Second")));
var answer = runtime.StreamAsync(new AskRequest
    { Model = "demo-chat", Prompt = "Say hello" });
using var stop = new CancellationTokenSource();
 
try
{
    await foreach (string text in answer.TextAsync(stop.Token))
    {
        Console.WriteLine(text);
        stop.Cancel();
    }
}
catch (OperationCanceledException) when (stop.IsCancellationRequested)
{
    Console.WriteLine("Canceled.");
}
Text
First
Canceled.

The short answer

Pass CancellationTokenSource.Token into the streaming call. When it’s time to stop, call Cancel() on the source. Handle OperationCanceledException around the await foreach, where the stream is actually consumed.

How do I cancel a stream in C#?

Pass the token at the point where your code starts streaming. In this example that’s script.StreamAsync(request, stop.Token). If you use OneLLM’s higher-level Runtime.StreamAsync, pass the token to TextAsync when you consume only the text. With either API, a Stop button can call Cancel() on the same source used by the running request. Use a fresh source for the next request; a canceled source doesn’t reset.

In the example, the loop doesn’t break after the first chunk. It asks for the next event so you can see that the scripted provider observes cancellation and throws. Breaking out would exit the loop without demonstrating that the provider saw the token. Canceling the stream doesn’t erase text you’ve already received: keep or discard partial text separately from how you mark the response as canceled.

How do you handle CancellationToken in a streaming test?

Queue more than one chunk, cancel after a known chunk, and check both the number of chunks and the exception. This sets the cancellation point without a timer or a race between tasks. The catch filter only treats the exception as expected when the example’s own source has requested cancellation. Leave other exceptions visible so a provider or programming error doesn’t look like a user clicking Stop.

The scripted provider exercises cancellation in process. It doesn’t tell you how quickly a remote service will respond to cancellation or whether work already happened on that service.

All onellm recipes