Skip to main content

How to Poll a Background Response from a Microsoft Agent Framework Agent in C#

· 13 min read
Jagdish Kumawat
Founder @ Dewiride

A long answer can take a model a while to write. With background responses turned on, a Microsoft Agent Framework agent's run can come back at once with a continuation token instead of the answer, and you ask again with that token until the answer is ready. Here's that loop in C#, with the time of every call.

Microsoft's guide describes the feature like this: This 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. This post does the polling.

Syntax​

Syntax
AgentRunOptions <options> = new() { AllowBackgroundResponses = true };
AgentResponse <response> = await <agent>.RunAsync(<message>, <session>, <options>);

while (<response>.ContinuationToken is not null)
{
await Task.Delay(<wait>);
<options>.ContinuationToken = <response>.ContinuationToken;
<response> = await <agent>.RunAsync(<session>, <options>);
}
PartWhat it is
<agent>An agent on the Responses API, such as one from AIProjectClient.AsAIAgent. Microsoft's guide: Currently, only agents that use the OpenAI Responses API support background responses
AllowBackgroundResponses = trueLets the run continue in the background. Its reference: When this property is set to true, non-streaming APIs may start a background operation and return an initial response with a continuation token.
<message>The question
<session>The conversation, from CreateSessionAsync. Every call gets the same one
<response>.ContinuationTokenGets or sets the continuation token for getting the result of a background agent response. It's null once the answer is ready
<wait>How long to wait before asking again, such as TimeSpan.FromSeconds(2)
<options>.ContinuationTokenThe token you pass back: Gets or sets the continuation token for resuming and getting the result of the agent response identified by this token.
RunAsync(<session>, <options>)The overload without a message. With a token in the options, it asks for that response again

Both ContinuationToken properties are experimental in Agent Framework 1.28, so the code that uses them goes between two #pragma lines. Step 3 shows them.

The Example​

A console app called PollBackground asks an agent named Explainer to Explain how a rainbow forms, in about 1,000 words., with background responses allowed. Until the answer is ready, it prints Not ready yet. with the seconds since it started, waits two seconds and asks again with the token. Then it prints how many words the answer has, and its first 200 characters.

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,353 output tokens, which comes to $0.00163.

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 PollBackground
cd PollBackground
Output (first command)
The template "Console App" was created successfully.

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

dotnet new console creates a console app in a new PollBackground 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:

PollBackground.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​

Replace everything in Program.cs with this:

Program.cs
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 explain how things work to children. Use plain text, without Markdown.",
name: "Explainer");
  • 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 for the deployment named in model. It works on the project's Responses API, which background responses need: Microsoft's Foundry provider page lists AIProjectClient.AsAIAgent(...) as its Responses Agent pattern.
  • using System.Diagnostics; is for the Stopwatch in the next step.

Step 3: Ask with Background Responses Allowed​

Add the question below the agent:

Program.cs (ask)
Stopwatch clock = Stopwatch.StartNew();
AgentSession session = await agent.CreateSessionAsync();
AgentRunOptions options = new() { AllowBackgroundResponses = true };

// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
AgentResponse response = await agent.RunAsync("Explain how a rainbow forms, in about 1,000 words.", session, options);
  • Stopwatch.StartNew() starts a clock, so each line the app prints can say how many seconds have passed.
  • CreateSessionAsync() creates the conversation. The question and every later call use this same session, as in Microsoft's sample.
  • AllowBackgroundResponses = true lets the agent work on the answer in the background. The call then comes back in one of two ways, which Microsoft's guide calls Immediate completion, with the final response and no token, and Background processing, with a token instead of the final result.
  • #pragma warning disable MEAI001 stops the compiler from reporting MEAI001 from this line on. AgentResponse.ContinuationToken and AgentRunOptions.ContinuationToken are experimental in Agent Framework 1.28, while AllowBackgroundResponses isn't, and without this line the build fails with error MEAI001: Fixed: MEAI001 'Microsoft.Agents.AI.AgentResponse.ContinuationToken' is for evaluation purposes only.
  • RunAsync(..., session, options) sends the question with those options.

Step 4: Ask Again Until the Token Is Null​

Add the loop below the question:

Program.cs (poll)
// A continuation token means the answer isn't ready yet: wait, then ask again with the token.
while (response.ContinuationToken is not null)
{
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Not ready yet.");
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}
#pragma warning restore MEAI001
  • while (response.ContinuationToken is not null) keeps asking as long as the response carries a token. Microsoft's guide says an absent token means the operation has completed, failed, or can't proceed further, so a null token ends the loop.
  • Console.WriteLine(...) prints the seconds so far and Not ready yet.
  • Task.Delay(TimeSpan.FromSeconds(2)) waits two seconds before asking again, like Microsoft's sample.
  • options.ContinuationToken = response.ContinuationToken puts the newest token into the same options object.
  • agent.RunAsync(session, options) asks for the response again, with no new message. Its reference: Run the agent with no message assuming that all required instructions are already provided to the agent or on the session. The token in the options tells it which response.
  • #pragma warning restore MEAI001 turns the check back on for the rest of the file.

When the loop ends, response holds the finished answer.

Step 5: Print the Answer​

Add the last two lines:

Program.cs (the answer)
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Ready: {response.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words.");
Console.WriteLine(response.Text[..Math.Min(response.Text.Length, 200)]);
  • The first line prints the seconds again and the answer's word count. Split(' ', StringSplitOptions.RemoveEmptyEntries) cuts the text at each space and drops the empty pieces, and Length counts the words that are left.
  • The second line prints the first 200 characters. [..n] takes the characters from the start up to n, and Math.Min keeps n inside a shorter answer.

Step 6: Run It​

Terminal
dotnet run
Output
[2.6 s] Not ready yet.
[5.7 s] Not ready yet.
[8.6 s] Not ready yet.
[11.5 s] Not ready yet.
[14.4 s] Ready: 1071 words.
A rainbow forms when sunlight shines through tiny drops of water in the air. The drops may come from rain, mist, a waterfall, a sprinkler, or even a garden hose. A rainbow looks like a colorful arc in

macOS-style terminal window titled Terminal — PollBackground showing dotnet run print the line Not ready yet. four times, at 2.6, 5.7, 8.6 and 11.5 seconds, then Ready: 1071 words. at 14.4 seconds, followed by the first 200 characters of the answer, which begins A rainbow forms when sunlight shines through tiny drops of water in the air.

  • At 2.6 seconds, the first call came back with a token instead of the answer: the agent was writing it in the background.
  • Each later line came about three seconds after the one before: the two-second wait plus the time the call took. The first three polls brought back a token each.
  • The fourth poll, at 14.4 seconds, brought the answer: 1,071 words, with no token, so the loop ended.

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​

Program.cs
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 explain how things work to children. Use plain text, without Markdown.",
name: "Explainer");

Stopwatch clock = Stopwatch.StartNew();
AgentSession session = await agent.CreateSessionAsync();
AgentRunOptions options = new() { AllowBackgroundResponses = true };

// Continuation tokens are experimental in Agent Framework 1.28 (MEAI001).
#pragma warning disable MEAI001
AgentResponse response = await agent.RunAsync("Explain how a rainbow forms, in about 1,000 words.", session, options);

// A continuation token means the answer isn't ready yet: wait, then ask again with the token.
while (response.ContinuationToken is not null)
{
Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Not ready yet.");
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}
#pragma warning restore MEAI001

Console.WriteLine($"[{clock.Elapsed.TotalSeconds:0.0} s] Ready: {response.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length} words.");
Console.WriteLine(response.Text[..Math.Min(response.Text.Length, 200)]);

macOS-style code window titled Program.cs — PollBackground showing an agent named Explainer created with AIProjectClient and AsAIAgent on the gpt-5.6-luna deployment, a stopwatch, a RunAsync call with AllowBackgroundResponses set to true, a while loop between two pragma lines for MEAI001 that waits two seconds and calls RunAsync again with the response's ContinuationToken until it is null, and two lines that print the word count and the first 200 characters of the answer

Common Mistakes​

MistakeWhat happensDo this instead
Treating the first response as the answerA response with a token isn't the answer yet: the token comes back while the result of the response has not been obtained yetAsk again until ContinuationToken is null
Asking again without a pauseMicrosoft's best practices ask for polling intervals that avoid overwhelming the serviceWait between calls, and longer when the answer takes long
Leaving out the two #pragma linesThe build fails with error MEAI001 (Fixed)Put the code that uses the tokens between disable and restore
Using an agent that isn't on the Responses APINo token comes back. 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 answer is ready straight away?​

Then the first call returns it without a token, and the loop never runs. Microsoft's guide: If no continuation token is returned, the operation is complete and the response contains the final result.

Does each poll cost more tokens?​

Not in this run. The Foundry project stored one response for the whole run, with its 39 input tokens and 1,353 output tokens. Each poll asked for that same response again; none of them sent the question to the model again.

How long should I wait between polls?​

The example waits a fixed two seconds, like Microsoft's sample. Microsoft's best practices add: Use exponential backoff for polling intervals if the operation is taking longer than expected. That means waiting a little longer after each answer that isn't ready yet.

Can I collect the answer after my app restarts?​

Yes. Save the token and the session, and poll from the next start: How to Collect a Microsoft Agent Framework Background Response After a Restart in C#.

Does streaming work with background responses?​

Yes, and there the tokens let you resume a stream that stopped: How to Resume an Interrupted Streaming Response from a Microsoft Agent Framework Agent in C#.

Conclusion​

To poll a background response, set AllowBackgroundResponses = true, and while the response has a ContinuationToken, wait, put the token into AgentRunOptions.ContinuationToken, and call RunAsync(session, options) again. A null token ends the loop. Here the 1,071-word answer arrived after 14.4 seconds and four polls, all of them reading one stored response.

Additional Resources​