How to Resume an Interrupted Streaming Response from a Microsoft Agent Framework Agent in C#
A streamed answer can stop halfway, when the connection drops or the client times out. With background responses turned on, a Microsoft Agent Framework agent's stream can be picked up again from the last update you received. Here's that resume in C#, with the exact point where the two streams join.
Microsoft's guide puts it like this: if the original stream gets interrupted, agents support stream resumption through continuation tokens. This post interrupts a stream and resumes it.
Syntax
AgentRunOptions <options> = new() { AllowBackgroundResponses = true };
AgentResponseUpdate? <lastUpdate> = null;
await foreach (AgentResponseUpdate <update> in <agent>.RunStreamingAsync(<message>, <session>, <options>))
{
<lastUpdate> = <update>;
// ...until the stream stops before its end
}
<options>.ContinuationToken = <lastUpdate>?.ContinuationToken;
await foreach (AgentResponseUpdate <update> in <agent>.RunStreamingAsync(<session>, <options>))
{
// ...the rest of the response
}
| Part | What it is |
|---|---|
<agent> | An agent on the Responses API, such as one from AIProjectClient.AsAIAgent |
AllowBackgroundResponses = true | Lets the response run in the background. Its reference: When this property is set to true, streaming APIs may also start a background operation and begin streaming response updates until the operation is completed. |
<message> | The question |
<session> | The conversation, from CreateSessionAsync. Both calls get the same one |
<update> | One piece of the streamed answer, an AgentResponseUpdate |
<lastUpdate> | The last update that arrived before the stream stopped |
<lastUpdate>?.ContinuationToken | Gets or sets the continuation token for resuming the streamed agent response of which this update is a part. |
<options>.ContinuationToken | Where the token goes for the second call: a continuation token obtained from the ContinuationToken of an update just before the interruption occurred can be passed to this property to resume the stream from the point of interruption. |
RunStreamingAsync(<session>, <options>) | The overload without a message. With a token in the options, it streams the rest of that response |
Only AgentRunOptions.ContinuationToken is experimental in Agent Framework 1.28, so only the line that sets it goes between two #pragma lines. Step 4 shows them.
The Example
A console app called ResumeStream asks an agent named Historian to Write a short history of the bicycle, in about 800 words., as a stream, with background responses allowed. A real stream stops because of something outside the app: Microsoft's guide names Operations that may be interrupted by network issues or client timeouts as one of the reasons to use background responses. So that there's something to resume, the example's own code stops reading after 30 updates, the way a dropped connection would end the stream. Then it resumes with the last update's token, reads the rest, and prints the point where the two streams join.
It calls a model, so it costs a little. The model is billed per token: gpt-5.6-luna on a Global Standard deployment costs $0.20 per million input tokens and $1.20 per million output tokens (How to Look Up Azure OpenAI Model Prices with the Azure Retail Prices API). The run in Step 6 used 39 input tokens and 1,277 output tokens, which comes to $0.00154.
Prerequisites
- The .NET 10 SDK.
- A Microsoft Foundry project with a deployed chat model, and the Foundry User role on it.
- The Azure CLI, signed in with
az login.
Step 1: Create a Console App
In a terminal, in the folder where you keep your projects, create the app and move into it:
dotnet new console -n ResumeStream
cd ResumeStream
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/ResumeStream/ResumeStream.csproj:
Restore succeeded.
dotnet new console creates a console app in a new ResumeStream folder, and cd moves into it. Then add two packages:
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.Foundryconnects Agent Framework to Microsoft Foundry, and brings in Agent Framework itself:Microsoft.Agents.AI1.28.0, which is generally available. The Foundry package's own version, 1.28.0-preview.261106.1, is a preview release.Azure.Identitysigns the app in with your Azure CLI account, so there's no key in the code.
The project file now has both packages:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Agents.AI.Foundry" Version="1.28.0-preview.261106.1" />
</ItemGroup>
</Project>
Step 2: Create the Agent
Replace everything in Program.cs with this:
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 write short histories for curious readers. Use plain text, without Markdown.",
name: "Historian");
AIProjectClientconnects to the Foundry project at that endpoint, andAzureCliCredentialsigns in with the account you used foraz login. Use your own project endpoint and model deployment.AsAIAgent(...)creates an agent for the deployment named inmodel. It works on the project's Responses API, which background responses need. Microsoft's guide: Currently, only agents that use the OpenAI Responses API support background responses, and its Foundry provider page listsAIProjectClient.AsAIAgent(...)as its Responses Agent pattern.
Step 3: Stream, and Stop Reading After 30 Updates
Add the session, the options and the first stream below the agent:
AgentSession session = await agent.CreateSessionAsync();
AgentRunOptions options = new() { AllowBackgroundResponses = true };
string text = "";
int updates = 0;
AgentResponseUpdate? lastUpdate = null;
// Read the stream until 30 updates have arrived, then stop reading, the way a dropped connection would.
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Write a short history of the bicycle, in about 800 words.", session, options))
{
text += update.Text;
lastUpdate = update;
if (++updates == 30)
{
break;
}
}
int stoppedAt = text.Length;
Console.WriteLine($"Stopped after {updates} updates and {stoppedAt} characters.");
CreateSessionAsync()creates the conversation. Both streams use this same session, as in Microsoft's sample.AllowBackgroundResponses = truelets the response run in the background. Then every update but the last comes with a token. The reference says agents that support background responses will return a continuation token on each update if background responses are allowed inAllowBackgroundResponses, except for the last update, for which the token will be null.text,updatesandlastUpdatehold the text so far, the number of updates, and the last update that arrived. The?inAgentResponseUpdate?meanslastUpdatecan benull, which it is until the first update arrives.RunStreamingAsync(..., session, options)sends the question and returns the answer as a stream of updates, andawait foreachreads them one at a time as they arrive.update.Textis the piece of text in that update.lastUpdate = updatekeeps the newest update. Its token is the one to resume from.if (++updates == 30)adds one to the count, then compares it. At the 30th update,breakleaves the loop, and the app reads nothing more from this stream. That's the interruption. Microsoft's own sample does the same with abreakafter the first update, under the comment// Simulate an interruption.stoppedAtkeeps the number of characters that arrived before the stop, for Step 5, and the next line prints both counts.
Step 4: Resume from the Last Update's Token
Add the resume below that:
// Resume from the last update's continuation token (experimental in Agent Framework 1.28: MEAI001).
#pragma warning disable MEAI001
options.ContinuationToken = lastUpdate?.ContinuationToken;
#pragma warning restore MEAI001
int resumedUpdates = 0;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(session, options))
{
text += update.Text;
resumedUpdates++;
}
#pragma warning disable MEAI001andrestorewrap one line only. That line setsAgentRunOptions.ContinuationToken, which is experimental in Agent Framework 1.28, whileAgentResponseUpdate.ContinuationToken, the token on each update, isn't. Without the two lines, the build fails witherror MEAI001: Fixed: MEAI001 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only.lastUpdate?.ContinuationTokenis the token of the last update that arrived. The?.givesnull, instead of an error, if no update arrived at all.RunStreamingAsync(session, options)has no message. Its reference: Runs the agent in streaming mode without providing new input messages, relying on existing context and instructions. With the token in the options, it streams the rest of the response that the token belongs to.- The loop adds each new update's text to
textand counts the updates inresumedUpdates.
When this loop ends, text holds both parts: what arrived before the stop and what arrived after it.
Step 5: Print Where the Two Streams Join
Add the last two lines:
Console.WriteLine($"Resumed: {resumedUpdates} more updates, {text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words in all.");
Console.WriteLine($"Where it joins: \"...{text[Math.Max(0, stoppedAt - 40)..stoppedAt]}|{text[stoppedAt..Math.Min(text.Length, stoppedAt + 40)]}...\"");
- The first line prints how many updates the resumed stream brought, and how many words the whole text has.
Split(' ', StringSplitOptions.RemoveEmptyEntries)cuts the text at each space and drops the empty pieces, andLengthcounts the words that are left. - The second line prints the 40 characters before the stop and the 40 after it, with a
|at the point where the first stream stopped.text[a..b]takes the characters from positionaup tob, andMath.MaxandMath.Minkeep both ends inside the text. Each\"puts a double quote into the printed line.
Step 6: Run It
dotnet run
Stopped after 30 updates and 160 characters.
Resumed: 95 more updates, 926 words in all.
Where it joins: "... of transforming travel, industry, sport|, and social life. Its history began not..."

- The first line: the first stream ended where the code stopped reading it. Its 30 updates had brought 160 characters of the history.
- The second line: the resumed stream brought 95 more updates, up to the end of the stream, and the whole history has 926 words.
- The third line: read without the
|, the two sides make one phrase,industry, sport, and social life. The resumed stream began right after the last update the app had read, with nothing repeated and nothing missing at the join.
Clean Up
The example creates no Azure resources, but the answer stays in your Foundry project. Background responses are always stored ones: the Responses API guide says Background mode requires store=true. Stateless requests are not supported. It also says By default, response data is retained for 30 days. To delete a response sooner, by its ID, see How to Delete a Stored Response in Microsoft Foundry with the Azure CLI.
The Complete File
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 write short histories for curious readers. Use plain text, without Markdown.",
name: "Historian");
AgentSession session = await agent.CreateSessionAsync();
AgentRunOptions options = new() { AllowBackgroundResponses = true };
string text = "";
int updates = 0;
AgentResponseUpdate? lastUpdate = null;
// Read the stream until 30 updates have arrived, then stop reading, the way a dropped connection would.
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Write a short history of the bicycle, in about 800 words.", session, options))
{
text += update.Text;
lastUpdate = update;
if (++updates == 30)
{
break;
}
}
int stoppedAt = text.Length;
Console.WriteLine($"Stopped after {updates} updates and {stoppedAt} characters.");
// Resume from the last update's continuation token (experimental in Agent Framework 1.28: MEAI001).
#pragma warning disable MEAI001
options.ContinuationToken = lastUpdate?.ContinuationToken;
#pragma warning restore MEAI001
int resumedUpdates = 0;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(session, options))
{
text += update.Text;
resumedUpdates++;
}
Console.WriteLine($"Resumed: {resumedUpdates} more updates, {text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words in all.");
Console.WriteLine($"Where it joins: \"...{text[Math.Max(0, stoppedAt - 40)..stoppedAt]}|{text[stoppedAt..Math.Min(text.Length, stoppedAt + 40)]}...\"");

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out AllowBackgroundResponses = true | No token is promised: the reference promises one on each update only when background responses are allowed in AllowBackgroundResponses | Set it to true in the options of the first call |
Leaving out the two #pragma lines | The build fails with error MEAI001 (Fixed) | Put the line that sets options.ContinuationToken between disable and restore |
| Using an agent that isn't on the Responses API | The reference: If the implementation does not support background responses, this property will be ignored. | Create the agent with AIProjectClient.AsAIAgent |
FAQ
What if the stream ends before it's interrupted?
Then there's nothing to resume. The reference says every update has a token except for the last update, for which the token will be null. And without a token, RunStreamingAsync(session, options) isn't a resume: it Runs the agent in streaming mode without providing new input messages, relying on existing context and instructions. So check that the saved token isn't null before you resume. The example doesn't check, because its answer was far from finished after 30 updates.
Does resuming cost more tokens?
Not in this run. The Foundry project stored one response for the whole run, with its 39 input tokens and 1,277 output tokens. The resumed stream read the rest of that same response; the question wasn't sent to the model again.
Is a background stream slower than a normal one?
The Responses API guide lists a known issue: Performance issues when background mode is used with streaming. Microsoft is working to resolve this issue. It also says Background responses currently have a higher time-to-first-token latency than synchronous responses. I didn't time this run.
Can a stream be resumed after the app restarts?
Microsoft's guide says to Keep the session and persist continuation tokens when the operation must survive a process restart. How to Collect a Microsoft Agent Framework Background Response After a Restart in C# saves both and collects the answer in a new process. It polls rather than streams, and I didn't test resuming a stream from a saved token.
Conclusion
To resume an interrupted streaming response, set AllowBackgroundResponses = true, keep the last update that arrived, put its ContinuationToken into AgentRunOptions.ContinuationToken, and call RunStreamingAsync(session, options) without a message. Here the first stream stopped after 30 updates and 160 characters, and the resumed stream brought the other 95 updates, starting at the exact character where the first one stopped.
Additional Resources
- Agent Background Responses — streaming background responses, and resuming them with continuation tokens.
- AgentResponseUpdate.ContinuationToken Property — the token on each update, and why the last one is
null. - AgentRunOptions.ContinuationToken Property — passing a token back to resume a stream or to poll.
- Use the Azure OpenAI Responses API — background streaming in the Responses API, and its known issues.
