Skip to main content

How to Collect a Microsoft Agent Framework Background Response After a Restart in C#

· 15 min read
Jagdish Kumawat
Founder @ Dewiride

A background response keeps being written after your app stops. Save the agent's session and the response's continuation token, and the next start of the app can collect the answer. Here's a C# console app that asks in one start, stops without waiting, and collects the answer in the next.

Syntax​

Syntax
// Before the app stops: save the session and the token.
JsonElement <saved> = await <agent>.SerializeSessionAsync(<session>);
await File.WriteAllTextAsync("<sessionFile>", <saved>.GetRawText());
await File.WriteAllBytesAsync("<tokenFile>", <response>.ContinuationToken.ToBytes().ToArray());

// In the next process: restore both, then poll.
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> = await <agent>.RunAsync(<session>, <options>);
PartWhat it is
<agent>An agent on the Responses API, built the same way in both processes
<session>The conversation the question was asked in
<response>The response that came back with a ContinuationToken instead of the answer
SerializeSessionAsync and GetRawText()The session as JSON, and that JSON as text
ToBytes()Gets the bytes representing this ResponseContinuationToken. ToArray() copies them into a byte[]
<sessionFile> and <tokenFile>The files that keep the session and the token between the two processes
DeserializeSessionAsyncTurns the saved JSON back into a session of the same agent
ResponseContinuationToken.FromBytesCreate a new instance of ResponseContinuationToken from the provided bytes.
RunAsync(<session>, <options>)The first poll in the new process. Keep polling until ContinuationToken is null

The Example​

A console app called CollectLater asks an agent named GardenGuide to Write a guide to growing tomatoes on a balcony, in about 1,000 words. The first start, dotnet run, asks with background responses allowed, saves the session to session.json and the token to answer.token, and ends. The second start, dotnet run -- collect, is a new process: it reads both files, asks for the answer until it's ready, prints how many words it has and how it starts, and deletes the files.

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 two starts made one background response, with 43 input tokens and 1,832 output tokens: $0.00221.

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:

Terminal
dotnet new console -n CollectLater
cd CollectLater
Output (first command)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/CollectLater/CollectLater.csproj:
Restore succeeded.

dotnet new console creates a console app in a new CollectLater folder, and cd moves into it. Then add two packages:

Terminal
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 connects Agent Framework to Microsoft Foundry, and brings in Agent Framework itself: Microsoft.Agents.AI 1.28.0, which is generally available. The Foundry package's own version, 1.28.0-preview.261106.1, is a preview release.
  • Azure.Identity signs the app in with your Azure CLI account, so there's no key in the code.

The project file now has both packages:

CollectLater.csproj
<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 and Name the Two Files​

Replace everything in Program.cs with this:

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

const string SessionFile = "session.json";
const string TokenFile = "answer.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 practical guides for home gardeners. Use plain text, without Markdown.",
name: "GardenGuide");
  • SessionFile and TokenFile are the names of the two files. A name without a folder means the folder you run the app from.
  • AIProjectClient connects to the Foundry project at that endpoint, and AzureCliCredential signs in with the account you used for az login. Use your own project endpoint and model deployment.
  • AsAIAgent(...) creates an agent on the project's Responses API, the kind of agent that supports background responses.
  • System.Text.Json has JsonSerializer and JsonElement for the session, and Microsoft.Extensions.AI has ResponseContinuationToken for the token.

Step 3: The First Start: Ask, Save and Stop​

The app does one of two things, depending on how you start it. Write the first start's part first. It's the else branch at the end of the file, so add it below the agent:

Program.cs (the first start, at the end of the file)
else
{
// Ask, save the session and the token, and stop without waiting for the answer.
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(
"Write a guide to growing tomatoes on a balcony, in about 1,000 words.",
session,
new AgentRunOptions { AllowBackgroundResponses = true });

if (response.ContinuationToken is null)
{
Console.WriteLine(response.Text);
return;
}

JsonElement savedSession = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(SessionFile, savedSession.GetRawText());
await File.WriteAllBytesAsync(TokenFile, response.ContinuationToken.ToBytes().ToArray());
Console.WriteLine($"Saved {SessionFile} and {TokenFile}. The answer is being written in the background.");
}
#pragma warning restore MEAI001
  • RunAsync(...) asks with AllowBackgroundResponses = true, so it can come back with a token before the answer is written.
  • if (response.ContinuationToken is null) handles a quick answer: it came back whole, without a token, so the app prints it and stops, with nothing to save.
  • SerializeSessionAsync(session) turns the session into JSON, and GetRawText() gives it as text for session.json. How to Save and Restore a Microsoft Agent Framework Session in C# covers saving and restoring a session in full.
  • response.ContinuationToken.ToBytes() gives the token as bytes, in a ReadOnlyMemory<byte>. ToArray() copies them into the byte[] that File.WriteAllBytesAsync writes to answer.token.
  • The last line says what happened, and the app ends without waiting for the answer.
  • #pragma warning restore MEAI001 closes the part of the file where the token properties are allowed. The next step adds where it opens.

Step 4: The Second Start: Read the Session and the Token​

Now add the second start's part between the agent and the else:

Program.cs (the second start, above the else)
// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
if (args.FirstOrDefault() == "collect")
{
// Read the session and the token that the first run saved, then ask for the answer until it's ready.
AgentSession session = await agent.DeserializeSessionAsync(
JsonSerializer.Deserialize<JsonElement>(await File.ReadAllTextAsync(SessionFile)));
AgentRunOptions options = new()
{
AllowBackgroundResponses = true,
ContinuationToken = ResponseContinuationToken.FromBytes(await File.ReadAllBytesAsync(TokenFile)),
};
  • #pragma warning disable MEAI001 opens the part of the file where the token properties are allowed. AgentResponse.ContinuationToken and AgentRunOptions.ContinuationToken are experimental in Agent Framework 1.28, and without this line the build fails with error MEAI001: Fixed: MEAI001 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only.
  • args.FirstOrDefault() == "collect" checks the word you typed after --. The dotnet run reference: All arguments after this delimiter are passed to the application run. FirstOrDefault() gives the first one, or null when there's none, so a plain dotnet run goes to the else.
  • DeserializeSessionAsync(...) turns the JSON from session.json back into a session of this agent.
  • ResponseContinuationToken.FromBytes(...) turns the bytes from answer.token back into a token, and puts it into the options with AllowBackgroundResponses = true.

Step 5: Poll, Then Delete the Files​

Below that, still above the else, add the rest of the second start:

Program.cs (poll, then delete the files)
AgentResponse response = await agent.RunAsync(session, options);
while (response.ContinuationToken is not null)
{
Console.WriteLine("Not ready yet.");
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}

File.Delete(SessionFile);
File.Delete(TokenFile);
Console.WriteLine($"Ready: {response.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words.");
Console.WriteLine(response.Text[..Math.Min(response.Text.Length, 200)]);
}
  • RunAsync(session, options) with the restored token asks for the response that the first start began. The loop is the same as in How to Poll a Background Response from a Microsoft Agent Framework Agent in C#: wait two seconds and ask again, until the token is null.
  • File.Delete removes both files once the answer is in: there's nothing left to collect.
  • The last two lines print the answer's word count and its first 200 characters.

That's the whole program: the second start's part, then the else with the first start's part.

Step 6: Start the App and Let It Stop​

Terminal
dotnet run
Output
Saved session.json and answer.token. The answer is being written in the background.

macOS-style terminal window titled Terminal — CollectLater showing dotnet run printing Saved session.json and answer.token. The answer is being written in the background. and ending

The app printed that line and ended. It left two small files of 135 and 167 bytes. Here they are, with the long values shortened:

session.json (the ID shortened)
{"conversationId":"resp_0e4d2e…","stateBag":{"InMemoryChatHistoryProvider":{"messages":[]}}}
answer.token (the token shortened)
{"type":"chatClientAgentContinuationToken","innerToken":"\u0022eyJyZXN…\u0022"}
  • session.json is the conversation. Its conversationId points at the history that Foundry keeps for it. The reference: Gets or sets the ID of the underlying service chat history to support cases where the chat history is stored by the agent service. That's why messages is empty.
  • answer.token is the token. type names the agent's token class, ChatClientAgentContinuationToken, which its reference describes as Represents a continuation token for ChatClientAgent operations. innerToken is the token of the chat client under the agent: Gets a continuation token provided by the underlying IChatClient. (\u0022 is a double quote, written as a JSON escape.) The app never reads inside the token: it saves what ToBytes gives and hands it back to FromBytes. Treat it the same way.

Why save both? Microsoft's guide says the token contains all necessary information to either poll for completion using the non-streaming agent API or resume an interrupted stream with streaming agent API. The session is the conversation: an AgentSession contains the state of a specific conversation with an agent, and the call that collects the answer updates it: The session will be updated with any response messages generated during invocation. The guide's advice for a restart names both: Keep the session and persist continuation tokens when the operation must survive a process restart.

Step 7: Collect the Answer in a New Process​

Terminal
dotnet run -- collect
Output
Not ready yet.
Not ready yet.
Not ready yet.
Not ready yet.
Ready: 1408 words.
Growing Tomatoes on a Balcony

Tomatoes are one of the most rewarding vegetables to grow in containers. A sunny balcony can provide enough space for a productive crop, even if you do not have a garden

macOS-style terminal window titled Terminal — CollectLater showing dotnet run -- collect printing Not ready yet. four times, then Ready: 1408 words. and the start of the answer, the title Growing Tomatoes on a Balcony followed by Tomatoes are one of the most rewarding vegetables to grow in containers.

  • A new process collected the answer that the first start asked for. Nothing from the first start was in memory, only the two files.
  • The answer was still being written: the first call with the saved token and the next three polls each brought back a token, so the app printed Not ready yet. four times. The fourth poll brought the answer: 1,408 words, starting with the title Growing Tomatoes on a Balcony.
  • Both files are gone afterwards, because the app deleted them.

Clean Up​

The example creates no Azure resources, and the second start already deleted session.json and answer.token. The answer stays in your Foundry project, though: background responses are always stored, because 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​

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

const string SessionFile = "session.json";
const string TokenFile = "answer.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 practical guides for home gardeners. Use plain text, without Markdown.",
name: "GardenGuide");

// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
if (args.FirstOrDefault() == "collect")
{
// Read the session and the token that the first run saved, then ask for the answer until it's ready.
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 = await agent.RunAsync(session, options);
while (response.ContinuationToken is not null)
{
Console.WriteLine("Not ready yet.");
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}

File.Delete(SessionFile);
File.Delete(TokenFile);
Console.WriteLine($"Ready: {response.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words.");
Console.WriteLine(response.Text[..Math.Min(response.Text.Length, 200)]);
}
else
{
// Ask, save the session and the token, and stop without waiting for the answer.
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(
"Write a guide to growing tomatoes on a balcony, in about 1,000 words.",
session,
new AgentRunOptions { AllowBackgroundResponses = true });

if (response.ContinuationToken is null)
{
Console.WriteLine(response.Text);
return;
}

JsonElement savedSession = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(SessionFile, savedSession.GetRawText());
await File.WriteAllBytesAsync(TokenFile, response.ContinuationToken.ToBytes().ToArray());
Console.WriteLine($"Saved {SessionFile} and {TokenFile}. The answer is being written in the background.");
}
#pragma warning restore MEAI001

macOS-style code window titled Program.cs — CollectLater showing the GardenGuide agent and two file names, session.json and answer.token. With the argument collect, the app restores the session with DeserializeSessionAsync and the token with ResponseContinuationToken.FromBytes, polls with RunAsync until the token is null, and deletes both files. Otherwise it asks with AllowBackgroundResponses set to true, and if a token comes back, saves the session with SerializeSessionAsync and the token's bytes with ToBytes before it ends

Common Mistakes​

MistakeWhat happensDo this instead
Restoring the session with a different agentThe reference warns that an AgentSession may not be reusable across different agents, since each agent may add different behaviors to the AgentSession it createsBuild the same agent in both starts
Treating the two files as harmlessThe reference warns that Serialized sessions may contain conversation content, session identifiers, and other potentially sensitive data including PII.Store them like other private data, and delete them once the answer is in
Leaving out the two #pragma linesThe build fails with error MEAI001 (Fixed)Put the code that uses the tokens between disable and restore

FAQ​

How long can the answer wait to be collected?​

The token points at a response stored in your Foundry project, and the Responses API guide says By default, response data is retained for 30 days. I didn't test how long a saved token keeps working.

Does the second start cost more tokens?​

No new answer is written. The two starts made one background response in the project, with 43 input tokens and 1,832 output tokens, $0.00221 in all.

What if the conversation goes on after the answer?​

Save the session again after collecting, with SerializeSessionAsync, because the call that collected the answer updated it. The example deletes both files because it asks one question only.

Conclusion​

To collect a background response after a restart, save two things when the run comes back with a token: the session, with SerializeSessionAsync, and the token's bytes, with ToBytes. In the next process, restore the session with DeserializeSessionAsync, turn the bytes back into a token with ResponseContinuationToken.FromBytes, and poll with RunAsync(session, options) until the token is null. Here a second start collected a 1,408-word answer that the first start never waited for.

Additional Resources​