Background Responses
A long answer can take the model longer to write than a client wants to wait, or than a connection stays up. With background responses, the agent returns a continuation token instead of an answer that isn't ready, and your app asks again with the token until it is, even from another process. This tutorial builds a bedtime story writer that polls for its story, collects one after the app that asked for it has ended, and resumes a stream it dropped.
How Background Responses Work
A token instead of an answer
Every RunAsync so far returned only when the model had finished writing: for a long answer, one request that stays open the whole time. Microsoft's guide lists where background responses help instead: complex tasks that need a lot of processing time, operations that network issues or client timeouts may interrupt, and long tasks you want to start now and check on later.
The feature enables agents to start processing a request and return a continuation token that can be used to poll for results or resume interrupted streams. You turn it on for a run with AllowBackgroundResponses = true in its AgentRunOptions, and the run then ends in one of two ways:
- Immediate completion. The answer was ready quickly, and the response holds it, with no token.
- Background processing. The work goes on in the background, and the response holds a continuation token instead of the answer.
A continuation token stands for work that isn't finished. Put it in AgentRunOptions.ContinuationToken for the next RunAsync, and the response is either a new token or the answer. A response without a token is the end: Microsoft's guide says that an absent token means the operation has completed, failed, or can't proceed further, for example, when user input is required.
Poll until there's no token
Asking again with the token until the answer comes is called polling:
The app waits a little between polls, so that it doesn't flood the service with requests. This tutorial waits 2 seconds.
A token can be saved
AgentResponse.ContinuationToken is a ResponseContinuationToken, and its ToBytes method turns it into bytes, which you can save. ResponseContinuationToken.FromBytes turns the bytes back into a token. So one process can start the work, save the token and end, and another can collect the answer later. Microsoft's best practices recommend it: Consider storing continuation tokens persistently for operations that may span user sessions. Step 5 saves the agent's session too, with SerializeSessionAsync from Sessions, and collects the answer in a new process.
A stream can resume
With RunStreamingAsync, from Streaming, the answer arrives as updates. With background responses allowed, every update except the last carries a continuation token, the API documentation says, and if the stream breaks, the last update's token picks it up again. Microsoft's guide: Each update includes a continuation token that captures the current state, allowing the stream to be resumed from exactly where it left off by passing this token to subsequent streaming API calls. Step 6 drops a stream on purpose, resumes it, and checks the join.
Which agents can do it
Microsoft's guide: Currently, only agents that use the OpenAI Responses API support background responses. AIProjectClient.AsAIAgent, used for every agent in these tutorials, creates a Responses Agent: an agent on Microsoft Foundry's Responses API. With an agent that doesn't support them, the setting does nothing. The API documentation of AllowBackgroundResponses: If the implementation does not support background responses, this property will be ignored.
In Foundry's Responses API, which does the work, a background request returns immediately with a response ID and a queued status, and the polls ask about that ID. Its guide also lists a limitation: Background mode requires store=true. Stateless requests are not supported. The agents in these tutorials already store their responses: as Sessions showed, Foundry keeps each response, and the session holds the newest one's ID. Step 5 finds that very ID inside a saved token.
The Example
A console app called StoryTime writes bedtime stories for children. It asks for "a bedtime story of about 1,500 words about a lighthouse keeper's cat", which takes the model a while to write. The final app has four modes, chosen by the word after dotnet run --:
- No word: ask, then poll in the same run until the story is ready.
start: ask, save the session and the token to two files, and end without waiting for the story.collect: in a new process, read the two files and poll until the story is ready.stream: stream the story, drop the stream on purpose after 50 updates, and resume it with the last update's token.
Each status line starts with the seconds since the app started, and every mode ends with the story's word count and its first 200 characters.
What It Costs
The model is gpt-5.6-luna, at $0.20 per million input tokens and $1.20 per million output tokens. I ran a copy of the app once more with its token usage printed: one story used 42 input tokens and 2,682 output tokens, about a third of a cent. Every story in this tutorial answers the same question, at about the same length.
Prerequisites
- The agent from Agent Skills, and the setup it uses: the .NET 10 SDK, the Azure CLI signed in, a Foundry project endpoint and a chat model deployment.
Step 1: Create a Console App
In a terminal, in the folder where you keep your projects, run:
dotnet new console -n StoryTime
cd StoryTime
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/StoryTime/StoryTime.csproj:
Restore succeeded.
info : PackageReference for package 'Microsoft.Agents.AI.Foundry' version '1.28.0-preview.261106.1' added to file '/Users/you/source/StoryTime/StoryTime.csproj'.
log : Restored /Users/you/source/StoryTime/StoryTime.csproj (in 1.34 sec).
info : PackageReference for package 'Azure.Identity' version '1.21.0' added to file '/Users/you/source/StoryTime/StoryTime.csproj'.
log : Restored /Users/you/source/StoryTime/StoryTime.csproj (in 1.05 sec).
The same two packages as in the previous tutorials. Microsoft.Agents.AI.Foundry, a preview, brings in Agent Framework, and with it everything this tutorial uses. Open the StoryTime folder in VS Code, or StoryTime.csproj in Visual Studio.
Step 2: Ask in the Background and Poll
Replace everything in Program.cs with:
using System.Diagnostics;
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 bedtime stories for children. Use plain text, without Markdown.",
name: "StoryTime");
// 1. Let the service work on the answer in the background.
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.CreateSessionAsync();
Stopwatch clock = Stopwatch.StartNew();
AgentResponse response = await agent.RunAsync(
"Write a bedtime story of about 1,500 words about a lighthouse keeper's cat.", session, options);
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] First answer: {Describe(response)}");
// 2. Ask again with the token until there is no token: then the answer is complete.
while (response.ContinuationToken is not null)
{
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Poll: {Describe(response)}");
}
string story = response.Text;
Console.WriteLine($"The story has {story.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words. It starts:");
Console.WriteLine(story[..Math.Min(story.Length, 200)]);
static string Describe(AgentResponse response) =>
response.ContinuationToken is null
? $"no token, {response.Text.Length} characters of text"
: $"a continuation token, {response.Text.Length} characters of text";
- The agent is created as in the earlier tutorials, with instructions for children's stories in plain text.
AllowBackgroundResponses = true(comment 1) allows a background response. The options are kept inoptions, because the loop changes them.- The first
RunAsyncsends the question, with the session and the options.Describereports what came back: a continuation token or none, and how many characters of text. - The loop (comment 2) runs while the response has a token. Each time, it waits 2 seconds with
Task.Delay, copies the token intooptions.ContinuationToken, and callsRunAsync(session, options)without a message: with a token in the options, the call polls the response that the token stands for. clock, aStopwatch, times each line from just before the first request. At the end, the app counts the story's words by splitting it at spaces, and prints its first 200 characters.
Run it:
dotnet run
Use your own project endpoint and model deployment.
/Users/you/source/StoryTime/Program.cs(24,8): error MEAI001: 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
/Users/you/source/StoryTime/Program.cs(27,5): error MEAI001: 'Microsoft.Agents.AI.AgentRunOptions.ContinuationToken' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
/Users/you/source/StoryTime/Program.cs(27,33): error MEAI001: 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
/Users/you/source/StoryTime/Program.cs(37,5): error MEAI001: 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
The build failed. Fix the build errors and run again.
The build failed with four MEAI001 errors, and each points at a place that reads or sets a continuation token: line 24 is the loop's condition, line 27 copies the token into the options, and line 37 is the check in Describe. The message calls these members "for evaluation purposes only": Microsoft marks them as experimental, and using them is an error until you suppress the diagnostic. I looked up which members of the feature carry the experimental mark, in Microsoft.Agents.AI.Abstractions 1.28.0 and Microsoft.Extensions.AI.Abstractions 10.11.0:
| Member | Experimental |
|---|---|
AgentRunOptions.AllowBackgroundResponses | No |
AgentRunOptions.ContinuationToken | Yes, MEAI001 |
AgentResponse.ContinuationToken | Yes, MEAI001 |
AgentResponseUpdate.ContinuationToken | No |
The ResponseContinuationToken type | No |
So turning background responses on builds, and polling with the token doesn't. Fixed: MEAI001 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only follows this error from my first build to the fix.
Step 3: Allow the Experimental Members
The fix is two lines around each place that uses a token. Replace everything from comment 2 to the end of the file with:
// 2. Ask again with the token until there is no token: then the answer is complete.
// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
while (response.ContinuationToken is not null)
{
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Poll: {Describe(response)}");
}
#pragma warning restore MEAI001
string story = response.Text;
Console.WriteLine($"The story has {story.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words. It starts:");
Console.WriteLine(story[..Math.Min(story.Length, 200)]);
#pragma warning disable MEAI001
static string Describe(AgentResponse response) =>
response.ContinuationToken is null
? $"no token, {response.Text.Length} characters of text"
: $"a continuation token, {response.Text.Length} characters of text";
#pragma warning restore MEAI001
#pragma warning disable MEAI001turns that one diagnostic off for the lines below it, and#pragma warning restore MEAI001turns it back on. Only the lines between them can use the experimental members without an error.- The new comment line says why the pragmas are there, for whoever reads the code next.
Run it again:
dotnet run
[3.6 s] First answer: a continuation token, 0 characters of text
[7.2 s] Poll: a continuation token, 0 characters of text
[10.2 s] Poll: a continuation token, 0 characters of text
[13.1 s] Poll: a continuation token, 0 characters of text
[15.9 s] Poll: a continuation token, 0 characters of text
[18.8 s] Poll: a continuation token, 0 characters of text
[21.8 s] Poll: no token, 11015 characters of text
The story has 1734 words. It starts:
Marmalade and the Sleeping Sea
At the very edge of the world, where the land became a long gray finger reaching into the sea, stood a lighthouse called Bellweather.
It was a tall, round tower painte

- The first answer came after 3.6 seconds, with a token and no text.
RunAsyncreturned before the story was written. - Five polls had a token and no text, about 3 seconds apart: the 2-second wait plus about a second for each request.
- At 21.8 seconds, a poll had no token, and the whole story: 11,015 characters, 1,734 words by the app's count.
The app still waited for its story, but in short requests, instead of one request that stays open until the last word. None of the polls brought part of the story: the text came all at once, in the response without a token.
Step 4: Give the App Four Modes
A token can also be saved, and a stream can be resumed. To try both, the app gets four modes. Replace everything in Program.cs with the blocks below, in this order. First, the top of the file:
using System.Diagnostics;
using System.Text.Json;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
const string Question = "Write a bedtime story of about 1,500 words about a lighthouse keeper's cat.";
const string SessionFile = "session.json";
const string TokenFile = "story.token";
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 bedtime stories for children. Use plain text, without Markdown.",
name: "StoryTime");
Stopwatch clock = Stopwatch.StartNew();
// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
switch (args.FirstOrDefault())
{
case "start":
await StartAsync();
break;
case "collect":
await CollectAsync();
break;
case "stream":
await StreamAsync();
break;
default:
await PollAsync();
break;
}
- Two new usings:
System.Text.Json, to read the saved session back, andMicrosoft.Extensions.AI, forResponseContinuationToken. Question,SessionFileandTokenFilehold the question and the names of the two files thatstartwrites andcollectreads. They're in the folder the app runs in: withdotnet run, the project folder.clockstarts before theswitch, so every mode times from the same point.- One
#pragma warning disable MEAI001covers all the code below it, up to therestoreat the end ofDescribe. - The
switchpicks the mode from the app's first argument. Without one,args.FirstOrDefault()returnsnull, which goes todefault: the polling of Step 3.
Next, the polling of Step 3, now a method:
// Asks, then polls in the same run until the story is complete.
async Task PollAsync()
{
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(Question, session, options);
Log($"First answer: {Describe(response)}");
while (response.ContinuationToken is not null)
{
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
Log($"Poll: {Describe(response)}");
}
PrintStory(response.Text);
}
Log prints a message with the seconds on the clock in front of it, and PrintStory prints the word count and the first 200 characters. Both are at the end of the file.
Then start, which asks and leaves the waiting to someone else:
// Asks, saves the session and the token, and stops without waiting for the story.
async Task StartAsync()
{
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(Question, session, new AgentRunOptions { AllowBackgroundResponses = true });
Log($"First answer: {Describe(response)}");
if (response.ContinuationToken is null)
{
PrintStory(response.Text);
return;
}
JsonElement savedSession = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(SessionFile, savedSession.GetRawText());
await File.WriteAllBytesAsync(TokenFile, response.ContinuationToken.ToBytes().ToArray());
Log($"Saved {SessionFile} and {TokenFile} ({new FileInfo(TokenFile).Length} bytes). The story is being written in the background.");
}
- Without a token, the story is already complete, so
startprints it and returns: that's immediate completion. - With a token,
SerializeSessionAsyncturns the session into JSON, as in Sessions, andGetRawTextwrites it tosession.json. ToBytes()gives the token's bytes as aReadOnlyMemory<byte>, andToArray()copies them into the array thatFile.WriteAllBytesAsyncwrites tostory.token.- The last line prints the token file's size, and
startends without waiting for the story.
Then collect, which picks up where start left off, in a new process:
// Reads the session and the token saved by "start", and polls until the story is complete.
async Task CollectAsync()
{
AgentSession session = await agent.DeserializeSessionAsync(
JsonSerializer.Deserialize<JsonElement>(await File.ReadAllTextAsync(SessionFile)));
AgentRunOptions options = new()
{
AllowBackgroundResponses = true,
ContinuationToken = ResponseContinuationToken.FromBytes(await File.ReadAllBytesAsync(TokenFile)),
};
AgentResponse response;
while (true)
{
response = await agent.RunAsync(session, options);
Log($"Poll: {Describe(response)}");
if (response.ContinuationToken is null)
{
break;
}
options.ContinuationToken = response.ContinuationToken;
await Task.Delay(TimeSpan.FromSeconds(2));
}
File.Delete(SessionFile);
File.Delete(TokenFile);
PrintStory(response.Text);
}
DeserializeSessionAsyncturns the saved JSON back into the session.JsonSerializer.Deserialize<JsonElement>reads the file's text into theJsonElementit takes.ResponseContinuationToken.FromBytesturns the saved bytes back into a token, equal to the one they came from, and the options carry it from the first request on.- The loop polls first and waits after. The story may already be finished by the time
collectruns, so the first request goes out at once. Without a token, the loop ends. Otherwise the new token replaces the old one, and the app waits 2 seconds. responseis declared before the loop, so the last response is still there afterbreak.File.Deleteremoves both files once the story is in: their token has done its job.

Then stream, which drops its stream on purpose and resumes it:
// Streams the story, drops the stream after 50 updates, and resumes it from the last update's token.
async Task StreamAsync()
{
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.CreateSessionAsync();
string story = "";
int updates = 0;
AgentResponseUpdate? lastUpdate = null;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(Question, session, options))
{
story += update.Text;
lastUpdate = update;
if (++updates == 50)
{
Log($"Stream dropped after {updates} updates and {story.Length} characters.");
break;
}
}
options.ContinuationToken = lastUpdate?.ContinuationToken;
int resumedUpdates = 0;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(session, options))
{
story += update.Text;
resumedUpdates++;
}
Log($"Resumed: {resumedUpdates} more updates.");
PrintStory(story);
}
RunStreamingAsync(Question, session, options)streams the story as updates, as in Streaming, here with background responses allowed. Each update's text goes ontostory, and the update itself intolastUpdate.- After 50 updates,
breakleaves the loop, and the app stops reading the stream. That's this app's stand-in for a dropped connection, like the break under "Simulate an interruption" in Microsoft's guide. options.ContinuationToken = lastUpdate?.ContinuationTokentakes the token of the last update that arrived.RunStreamingAsync(session, options), without a message, resumes the stream from there, and its updates go onto the samestory, counted inresumedUpdates.
Last, the end of the file:
static string Describe(AgentResponse response) =>
response.ContinuationToken is null
? $"no token, {response.Text.Length} characters of text"
: $"a continuation token, {response.Text.Length} characters of text";
#pragma warning restore MEAI001
void Log(string message) => Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] {message}");
static void PrintStory(string story)
{
Console.WriteLine($"The story has {story.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words. It starts:");
Console.WriteLine(story[..Math.Min(story.Length, 200)]);
}
Describe is the same as before, and the restore after it closes the region that the disable at the top opened. Log and PrintStory print what Step 3 printed with Console.WriteLine.
Step 5: Start Now, Collect Later
Run the start mode:
dotnet run -- start
-- tells dotnet run that the words after it are for the app, so start arrives in args.
[2.8 s] First answer: a continuation token, 0 characters of text
[2.8 s] Saved session.json and story.token (167 bytes). The story is being written in the background.
The app got a token after 2.8 seconds, saved both files, and ended. The project folder now holds them. Here's session.json, with the response ID shortened:
{"conversationId":"resp_084b…","stateBag":{"InMemoryChatHistoryProvider":{"messages":[]}}}
And story.token, with most of its base64 text left out:
{"type":"chatClientAgentContinuationToken","innerToken":"\u0022eyJyZXNwb25zZUlkIjoi…\u0022"}
- The token's bytes are JSON: a
type, and aninnerToken. TheinnerTokentext starts and ends with\u0022, a JSON escape for a double quote, and between them is base64 text. - Decoded, the base64 is
{"responseId":"resp_084b…"}: the ID of the story's response in Foundry. - The session's
conversationIdis that same ID. The token and the session both point at the story's response.
A session can hold more than an ID. The API documentation warns that Serialized sessions may contain conversation content, session identifiers, and other potentially sensitive data including PII, and asks you to Treat serialized session data as sensitive and store it securely with appropriate access controls and encryption at rest. Two files in a project folder are fine for this tutorial. In a real app, keep them where only the app can read them.
Now collect the story, in a new process:
dotnet run -- collect
I ran it right after start:
[2.2 s] Poll: a continuation token, 0 characters of text
[5.1 s] Poll: a continuation token, 0 characters of text
[8.0 s] Poll: no token, 10617 characters of text
The story has 1681 words. It starts:
The Lighthouse Keeper’s Cat
At the very edge of a small green island stood a white lighthouse with a red roof.
It stood on a hill above the sea, where the waves curled and tumbled over black rocks.

- A new process, with a new clock. Its first poll, at 2.2 seconds, still got a token: the story wasn't finished yet.
- One more poll with a token, then the story at 8.0 seconds: 10,617 characters and 1,681 words, under a different title from Step 3's story, because every run asks the model afresh.
- Both files are gone.
collectdeleted them once it had the story.
The process that collected the story never asked for it. All it had was a token and a session, read from two files.
Step 6: Drop a Stream and Resume It
Run the stream mode:
dotnet run -- stream
[15.4 s] Stream dropped after 50 updates and 532 characters.
[33.1 s] Resumed: 141 more updates.
The story has 1665 words. It starts:
The Cat Who Kept the Light
On the edge of the sea, where the waves curled around black rocks and the gulls cried into the wind, there stood a tall white lighthouse.
It had a red roof, a round window
The first stream gave 532 characters in 50 updates before the app dropped it at 15.4 seconds, the resumed stream brought 141 more updates, and the story came to 1,665 words. But a repeated or a missing piece would be at the drop, and this output doesn't show the drop. So I added two lines to StreamAsync. After the first await foreach loop, just above the line that sets options.ContinuationToken, add a line that remembers where the first stream's text ended:
int dropAt = story.Length;
And after the line that logs Resumed, add one that prints 40 characters on each side of that point, with a | where the first stream ended:
Console.WriteLine($"Around the drop: \"...{story[Math.Max(0, dropAt - 40)..dropAt]}|{story[dropAt..Math.Min(story.Length, dropAt + 40)]}...\"");
story[a..b] uses a C# range to take the characters from position a up to, but not including, position b. Math.Max and Math.Min keep both ranges inside the story. The complete file is now:
using System.Diagnostics;
using System.Text.Json;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
const string Question = "Write a bedtime story of about 1,500 words about a lighthouse keeper's cat.";
const string SessionFile = "session.json";
const string TokenFile = "story.token";
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 bedtime stories for children. Use plain text, without Markdown.",
name: "StoryTime");
Stopwatch clock = Stopwatch.StartNew();
// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
switch (args.FirstOrDefault())
{
case "start":
await StartAsync();
break;
case "collect":
await CollectAsync();
break;
case "stream":
await StreamAsync();
break;
default:
await PollAsync();
break;
}
// Asks, then polls in the same run until the story is complete.
async Task PollAsync()
{
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(Question, session, options);
Log($"First answer: {Describe(response)}");
while (response.ContinuationToken is not null)
{
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
Log($"Poll: {Describe(response)}");
}
PrintStory(response.Text);
}
// Asks, saves the session and the token, and stops without waiting for the story.
async Task StartAsync()
{
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(Question, session, new AgentRunOptions { AllowBackgroundResponses = true });
Log($"First answer: {Describe(response)}");
if (response.ContinuationToken is null)
{
PrintStory(response.Text);
return;
}
JsonElement savedSession = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(SessionFile, savedSession.GetRawText());
await File.WriteAllBytesAsync(TokenFile, response.ContinuationToken.ToBytes().ToArray());
Log($"Saved {SessionFile} and {TokenFile} ({new FileInfo(TokenFile).Length} bytes). The story is being written in the background.");
}
// Reads the session and the token saved by "start", and polls until the story is complete.
async Task CollectAsync()
{
AgentSession session = await agent.DeserializeSessionAsync(
JsonSerializer.Deserialize<JsonElement>(await File.ReadAllTextAsync(SessionFile)));
AgentRunOptions options = new()
{
AllowBackgroundResponses = true,
ContinuationToken = ResponseContinuationToken.FromBytes(await File.ReadAllBytesAsync(TokenFile)),
};
AgentResponse response;
while (true)
{
response = await agent.RunAsync(session, options);
Log($"Poll: {Describe(response)}");
if (response.ContinuationToken is null)
{
break;
}
options.ContinuationToken = response.ContinuationToken;
await Task.Delay(TimeSpan.FromSeconds(2));
}
File.Delete(SessionFile);
File.Delete(TokenFile);
PrintStory(response.Text);
}
// Streams the story, drops the stream after 50 updates, and resumes it from the last update's token.
async Task StreamAsync()
{
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.CreateSessionAsync();
string story = "";
int updates = 0;
AgentResponseUpdate? lastUpdate = null;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(Question, session, options))
{
story += update.Text;
lastUpdate = update;
if (++updates == 50)
{
Log($"Stream dropped after {updates} updates and {story.Length} characters.");
break;
}
}
int dropAt = story.Length;
options.ContinuationToken = lastUpdate?.ContinuationToken;
int resumedUpdates = 0;
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(session, options))
{
story += update.Text;
resumedUpdates++;
}
Log($"Resumed: {resumedUpdates} more updates.");
Console.WriteLine($"Around the drop: \"...{story[Math.Max(0, dropAt - 40)..dropAt]}|{story[dropAt..Math.Min(story.Length, dropAt + 40)]}...\"");
PrintStory(story);
}
static string Describe(AgentResponse response) =>
response.ContinuationToken is null
? $"no token, {response.Text.Length} characters of text"
: $"a continuation token, {response.Text.Length} characters of text";
#pragma warning restore MEAI001
void Log(string message) => Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] {message}");
static void PrintStory(string story)
{
Console.WriteLine($"The story has {story.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words. It starts:");
Console.WriteLine(story[..Math.Min(story.Length, 200)]);
}
And the project file, as dotnet new and the two dotnet add package commands left it:
<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>
Run the stream again:
dotnet run -- stream
[15.0 s] Stream dropped after 50 updates and 553 characters.
[34.2 s] Resumed: 137 more updates.
Around the drop: "...hthouse keeper was named Mr. Rowan.
Mr.| Rowan lived in a small house beside the..."
The story has 1663 words. It starts:
The Cat Who Kept the Light
At the very edge of the sea, where the waves curled around black rocks and the gulls cried into the wind, stood a tall white lighthouse.
It had a red roof, a round balcony

- The first stream brought 553 characters in 50 updates, by 15.0 seconds, and the app dropped it there.
- The resumed stream brought 137 more updates, to the end, at 34.2 seconds.
- Around the drop, the first stream ended with "Mr." and the resumed one began with " Rowan lived in a small house". "Mr. Rowan" reads on, with no word repeated and none missing.
- The streamed story took longer than the polled one in Step 3: 34.2 seconds against 21.8. Microsoft's Responses API guide lists Performance issues when background mode is used with streaming among its known issues, and notes that Background responses currently have a higher time-to-first-token latency than synchronous responses.
What You Can Do Now
- Explain what a continuation token is, and why a response without one is complete.
- Let an agent answer in the background with
AllowBackgroundResponses, and poll until the answer is in. - Save a token with
ToBytesand a session withSerializeSessionAsync, and collect the answer in another process. - Resume a dropped stream from the last update's token, and check where the two streams meet.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using the token properties without suppressing MEAI001 | error MEAI001: ... is for evaluation purposes only, and the build fails (Fixed) | Put #pragma warning disable MEAI001 and restore around the lines that use them |
Reading response.Text after the first RunAsync | It's empty while the response has a token, as in every first answer here | Poll until ContinuationToken is null, then read the text |
| Polling with no wait between requests | Every poll is one more request to the service | Wait between polls, and wait longer when the work takes long |
| Allowing background responses on an agent that doesn't support them | The setting is ignored, and the run waits for the whole answer | Use a Responses Agent, such as the one AIProjectClient.AsAIAgent creates |
| Keeping only the text of a stream that dropped | There's no token left to resume it with | Keep the last update, as StreamAsync does, or its token |
| Leaving saved sessions and tokens where others can read them | A saved session can hold conversation content and IDs | Store them with access controls and encryption at rest |
Frequently Asked Questions
What if the first answer has no token?
Then the answer is already complete: that's immediate completion, and response.Text holds it. The loop in Step 3 doesn't run at all, and start prints the story instead of saving files. Microsoft's guide also notes that some agents don't let you choose: These agents can decide autonomously whether to initiate a background response based on the complexity of the operation, regardless of the AllowBackgroundResponses setting. So check for a token every time, rather than expect one.
How long should I wait between polls?
Microsoft's best practices are to Implement appropriate polling intervals to avoid overwhelming the service, and to Use exponential backoff for polling intervals if the operation is taking longer than expected: wait longer after each poll that still brings a token. This tutorial waits a fixed 2 seconds, and the story in Step 3 needed six polls.
Why are the token properties experimental?
Microsoft marks them that way, and the error message says what that means: they're "for evaluation purposes only and ... subject to change or removal in future updates". So code that uses them may need changes when you update Agent Framework. AllowBackgroundResponses, AgentResponseUpdate.ContinuationToken and the token type itself aren't experimental.
Does a Harness agent work the same way?
Yes. A Harness agent, which What Is Microsoft Agent Framework? introduces, takes the same run options, but Microsoft's guide points out that Harness construction doesn't enable provider background responses automatically: set AllowBackgroundResponses when you start the run. Its advice for work that has to outlast the app: Keep the session and persist continuation tokens when the operation must survive a process restart.
Conclusion
Background responses let a long answer happen without one long request. With AllowBackgroundResponses, an agent on the Responses API returns a continuation token while the answer isn't ready, and each RunAsync with the token brings either a new token or the answer. A token turns into bytes you can save, so with the session, another process can collect the answer, and each streamed update carries one, so a dropped stream picks up where it stopped. In Agent Framework 1.28, the members that read and set the token are experimental, so suppress MEAI001 around the lines that use them.
Next: Observability (coming soon) — traces, metrics and logs with OpenTelemetry.
Additional Resources
- Agent Background Responses — polling, stream resumption and the best practices.
- Background tasks in the Responses API — the service's background mode, its limitations and its known issues.
- Microsoft Foundry model provider — the Responses Agent that
AIProjectClient.AsAIAgentcreates. - ResponseContinuationToken class — the token type, with
ToBytesandFromBytes. - Background Responses sample — Microsoft's complete working example, linked from its guide.