Skip to main content

How to Stop a Streaming Microsoft Agent Framework Agent Run Early in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

Sometimes you don't need the rest of an answer: the person pressed Stop, or you already have what you asked for. A streamed agent run can be stopped halfway with a CancellationToken, and the run tells you it was cut short.

Syntax​

Syntax
using CancellationTokenSource <stop> = new();

try
{
await foreach (AgentResponseUpdate <update> in <agent>.RunStreamingAsync(<message>, cancellationToken: <stop>.Token))
{
// … when you have enough:
<stop>.Cancel();
}
}
catch (OperationCanceledException)
{
// The run was stopped before it finished.
}
PartWhat it is
CancellationTokenSourceThe switch. Its Token goes to the run, and Cancel() flips it
cancellationToken:The parameter of RunStreamingAsync that takes the token. Microsoft's reference: The CancellationToken to monitor for cancellation requests.
<stop>.Cancel()Asks the run to stop. Call it from anywhere: inside the loop, a timer, or a Stop button
OperationCanceledExceptionWhat the stream throws when it stops because of the token

The Example​

An agent is asked to Count from 1 to 50, one number per line. The app prints the numbers as they stream in, and stops the run as soon as it has seen 10.

Prerequisites​

  • A model deployment in a Microsoft Foundry project, and the Foundry User role on the Foundry resource for your account. The app calls the model as you.
  • The .NET 10 SDK (dotnet --version prints a version that starts with 10.0) and the Azure CLI, signed in with az login.

Step 1: Create a Console App​

Terminal
dotnet new console -n CountToFifty
cd CountToFifty
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0

Microsoft.Agents.AI.Foundry turns a model in a Foundry project into an agent, and brings in Agent Framework. Azure.Identity signs the app in with your Azure CLI sign-in. Open the folder in VS Code, or CountToFifty.csproj in Visual Studio.

Step 2: Stream with a Token, and Cancel It​

Replace everything in Program.cs:

Program.cs
using System.Diagnostics;
using System.Text;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;

AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(model: "gpt-5.6-luna", instructions: "You count out loud.", name: "Counter");

// 1. The switch that stops the run. Pass its token to RunStreamingAsync.
using CancellationTokenSource stop = new();
StringBuilder answer = new();
Stopwatch clock = Stopwatch.StartNew();

try
{
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(
"Count from 1 to 50, one number per line.", cancellationToken: stop.Token))
{
answer.Append(update.Text);
Console.Write(update.Text);

// 2. Enough: once the answer reaches 10, flip the switch.
if (answer.ToString().Split('\n').Contains("10"))
{
stop.Cancel();
}
}

Console.WriteLine();
Console.WriteLine("The run finished by itself.");
}
catch (OperationCanceledException)
{
// 3. The run stops with OperationCanceledException: that's how you know it was cut short.
Console.WriteLine();
Console.WriteLine($"Stopped after {clock.Elapsed.TotalSeconds:0.0} s, with {answer.Length} characters of the answer.");
}
  • stop.Token goes to RunStreamingAsync through cancellationToken:. The run watches it.
  • answer collects the text, so the app can check what has arrived. Split('\n').Contains("10") is true once 10 is on a line of its own.
  • stop.Cancel() asks the run to stop. The await foreach then ends with an OperationCanceledException instead of the next update.
  • The catch is the normal path for a stopped run, not an error. The message after the loop only prints if the run finished by itself.

Use your own Foundry project endpoint and model deployment.

Step 3: Run It​

Run dotnet run in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Output
1
2
3
4
5
6
7
8
9
10

Stopped after 3.3 s, with 21 characters of the answer.

macOS-style terminal window titled Terminal — CountToFifty showing the numbers 1 to 10, one per line, then Stopped after 3.3 s, with 21 characters of the answer.

The agent was asked for 50 numbers and the app stopped it at 10: the next step of the loop threw OperationCanceledException, and the catch reported where it stopped. The 21 characters are the nine numbers from 1 to 9 with their line breaks, then 10 and its line break.

The Complete File​

macOS-style code window titled Program.cs showing the CountToFifty app: a CancellationTokenSource named stop, an await foreach over agent.RunStreamingAsync with cancellationToken stop.Token that appends and prints each update's text and calls stop.Cancel() once a line equals 10, and a catch for OperationCanceledException that prints how long the run took and how many characters arrived

Program.cs from Step 2 is the whole program.

Common Mistakes​

MistakeWhat happensDo this instead
Creating the token but not passing it to RunStreamingAsyncCancel() stops nothing, and the whole answer streamsPass cancellationToken: stop.Token
No catch for OperationCanceledExceptionThe app ends with an unhandled exception when you stop the runCatch it, and treat it as a stopped run
Catching every exception the same wayA real error looks like a stopCatch OperationCanceledException separately
Forgetting using on the CancellationTokenSourceIt isn't disposed when you're doneDeclare it with using

FAQ​

Can I stop a run after a time limit instead?​

Yes. A CancellationTokenSource can cancel itself after a delay: create it with a TimeSpan, or call CancelAfter, and pass its token the same way. I tried new CancellationTokenSource(TimeSpan.FromSeconds(3)) without the check for 10: the run stopped after 3.0 seconds, at the number 3, through the same catch.

Does RunAsync take a token too?​

Yes, the same cancellationToken parameter. With RunAsync there's nothing to show before the end, so stopping it means getting no answer at all.

Where is this used in a real app?​

Behind a Stop button. In a web app, the token can come from the request: ASP.NET Core cancels HttpContext.RequestAborted when the browser goes away, so a run that nobody is reading stops too.

Conclusion​

To stop a streamed agent run early, create a CancellationTokenSource, pass its Token to RunStreamingAsync with cancellationToken:, and call Cancel() when you have enough. The stream then ends with an OperationCanceledException: catch it, and you know the run was cut short on purpose.

Additional Resources​