Skip to main content

How to Share Data Between the Steps of a Microsoft Agent Framework Workflow in C#

· 14 min read
Jagdish Kumawat
Founder @ Dewiride

A step in a Microsoft Agent Framework workflow can keep a value in the workflow's state with QueueStateUpdateAsync, and a later step can read it with ReadStateAsync, so the value doesn't have to travel in the message between them. Both calls take a scope name, and the scope decides who sees the value: leave it out, and each step reads and writes a scope of its own. Here's that mistake in a small C# app, and the change that fixed it.

Microsoft's State guide sums up what state is for: State allows multiple executors within a workflow to access and modify common data. An executor is one step of a workflow. Each step gets a message from the step before it, but a later step sometimes needs something that message doesn't carry, and the guide goes on: This feature is essential for scenarios where different parts of the workflow need to share information where direct message passing is not feasible or efficient.

Syntax​

Syntax
// In one step: keep a value in the workflow's state
await context.QueueStateUpdateAsync("<key>", <value>, "<scopeName>", <cancellationToken>);

// In a later step: read the value back
<Type>? <variable> = await context.ReadStateAsync<<Type>>("<key>", "<scopeName>", <cancellationToken>);
PartWhat it is
contextThe IWorkflowContext that the step's handler receives, documented as Provides services for an Executor during the execution of a workflow.
QueueStateUpdateAsyncQueues a new value for a key. Its documentation: Subsequent reads by this executor will result in the new value of the state. Other executors will only see the new state starting from the next SuperStep.
"<key>"The name the value is kept under. The step that reads it uses the same key.
<value>The value to keep: The value to set for the queue entry.
"<scopeName>"The scope the value is written to, or read from: An optional name that specifies the scope to update. If null, the default scope is used.
<cancellationToken>The CancellationToken that the handler receives, so the call stops if the run is cancelled.
ReadStateAsync<<Type>>Reads a state value from the workflow's state store. When the scope holds nothing under the key, a string comes back as null.
<Type> and <variable>The type of the value, and your variable for it.

The scope name is the part that's easy to get wrong. The State guide: If scopeName is null, the executor's private default scope is used. And: If scopeName is set (for example, "SharedResponse"), the value is written to a shared scope that any executor can read when using the same scope name.

The Example​

A console app called SentenceStats runs a workflow of two steps on the sentence Workflows pass messages between steps. The first step, CountWords, counts the words and sends the count on. The second, DescribeCount, receives only that count, so it reads the sentence from the workflow's state, where CountWords kept it, and returns a line such as "Workflows pass messages between steps" has 5 words. The first version leaves out the scope name, and the second step gets no sentence. Step 8 makes the change that fixes it. There's no AI model in it, so you don't need an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

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

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

dotnet new console creates a console app in a new SentenceStats folder, and cd moves into it. Open the folder in VS Code, or SentenceStats.csproj in Visual Studio.

Step 2: Add the Workflows Package​

Terminal
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
Output
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/timestampctl.pem'.
info : Adding PackageReference for package 'Microsoft.Agents.AI.Workflows' into project '/Users/you/source/SentenceStats/SentenceStats.csproj'.
info : Restoring packages for /Users/you/source/SentenceStats/SentenceStats.csproj...
info : CACHE https://api.nuget.org/v3/vulnerabilities/index.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/vulnerability.base.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.30.23.39.07/2026.12.03.05.39.24/vulnerability.update.json
info : Package 'Microsoft.Agents.AI.Workflows' is compatible with all the specified frameworks in project '/Users/you/source/SentenceStats/SentenceStats.csproj'.
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/SentenceStats/SentenceStats.csproj'.
info : Generating MSBuild file /Users/you/source/SentenceStats/obj/SentenceStats.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/SentenceStats/obj/project.assets.json
log : Restored /Users/you/source/SentenceStats/SentenceStats.csproj (in 770 ms).

Microsoft.Agents.AI.Workflows has everything a workflow is made of: its steps, the edges that connect them, the builder, the code that runs a workflow, and the state this guide uses. --version keeps you on the version this guide used. The project file now references it:

SentenceStats.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
</ItemGroup>

</Project>

The two steps in this guide are plain functions, so this one package is all the project needs.

Step 3: Write the Step That Keeps the Sentence​

Replace everything in Program.cs with the first step:

Program.cs
using Microsoft.Agents.AI.Workflows;

Func<string, IWorkflowContext, CancellationToken, ValueTask<int>> count = async (sentence, context, cancellationToken) =>
{
// Keep the sentence in the workflow's state, so a later step can read it.
await context.QueueStateUpdateAsync("sentence", sentence, cancellationToken: cancellationToken);
return sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
};
  • Func<string, IWorkflowContext, CancellationToken, ValueTask<int>> count is a function that takes a string, the workflow context and a cancellation token, and returns an int asynchronously. Step 5 turns it into a workflow step.
  • QueueStateUpdateAsync("sentence", sentence, cancellationToken: cancellationToken) keeps the sentence in the workflow's state under the key sentence. It passes the token by name and no scope name, so the value goes to the default scope.
  • The return line splits the sentence at its spaces, drops any empty pieces, and returns how many words are left.

Step 4: Write the Step That Reads It​

Add the second step below the first:

Program.cs (add below the first step)
Func<int, IWorkflowContext, CancellationToken, ValueTask<string>> describe = async (words, context, cancellationToken) =>
{
// The message brings only the count. The sentence comes from the state.
string? sentence = await context.ReadStateAsync<string>("sentence", cancellationToken: cancellationToken);
return $"\"{sentence}\" has {words} words.";
};
  • Func<int, IWorkflowContext, CancellationToken, ValueTask<string>> describe takes an int, the count that the first step returns, and returns a string.
  • ReadStateAsync<string>("sentence", cancellationToken: cancellationToken) reads the string kept under the key sentence, again without a scope name. string? lets the variable hold null, for when nothing is there.
  • The return line puts the sentence between quotes, written \" inside the string, and adds the count.

Step 5: Connect the Steps and Run the Workflow​

Add this at the end of the file:

Program.cs (add at the end)
ExecutorBinding countWords = count.BindAsExecutor("CountWords");
ExecutorBinding describeCount = describe.BindAsExecutor("DescribeCount");

Workflow workflow = new WorkflowBuilder(countWords)
.AddEdge(countWords, describeCount)
.WithOutputFrom(describeCount)
.Build();

await using Run run = await InProcessExecution.RunAsync(workflow, "Workflows pass messages between steps");

foreach (WorkflowOutputEvent output in run.OutgoingEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}
  • BindAsExecutor("CountWords") turns a function into a workflow step with the id CountWords. Its documentation: Configures a function-based asynchronous message handler as an executor with the specified identifier and options.
  • new WorkflowBuilder(countWords) starts the workflow at CountWords, so CountWords receives the input. AddEdge sends what CountWords returns on to DescribeCount, and WithOutputFrom(describeCount) makes what DescribeCount returns the workflow's output.
  • InProcessExecution.RunAsync runs the workflow inside the app, with the sentence as its input: The workflow will run until its first halt, and the returned Run will capture all outgoing events. await using disposes of the run when the app is done with it.
  • The loop prints the data of each WorkflowOutputEvent, the event that carries the workflow's output.

Step 6: Run It​

Terminal
dotnet run
Output
Output: "" has 5 words.

macOS-style terminal window titled Terminal — SentenceStats showing dotnet run printing Output: with an empty pair of quotes where the sentence should be, followed by has 5 words

The count is right, but the sentence is missing. DescribeCount got its 5 in the message, and found nothing under sentence in the state.

Step 7: Find Out Why the Second Step Read Nothing​

Timing isn't the cause. QueueStateUpdateAsync's documentation says other steps see a new value starting from the next SuperStep. A superstep is one round of the run, and Microsoft's guide to the execution model lists what each round does, ending with: Queues any new messages emitted by executors for the next superstep. So CountWords ran in one superstep, and the count it returned reached DescribeCount in the next, which is exactly when another step can see the new value.

The cause is the scope. Neither call named one, so each used its own step's default scope. The documentation of ScopeId, the type that identifies a scope, says whose scope that is: If a scope name is not provided, it references the default scope private to the executor. Otherwise, regardless of the executorId, it references a shared scope with the specified name.

So CountWords kept the sentence in a scope that belongs to CountWords, and DescribeCount looked in a scope that belongs to DescribeCount, which has nothing under sentence. ReadStateAsync returned null, and C# writes a null in an interpolated string as nothing: The string interpolation for a null expression is the empty string. That's the empty pair of quotes in the output.

Step 8: Give Both Steps One Shared Scope​

The State guide gives the rule: To share state across executors, use the same non-null scope name in both write and read calls. Add a scope name below the using line:

Program.cs (below the using line)
// One scope name for both steps: without it, each step reads and writes a scope of its own.
const string Scope = "stats";

Then pass it to both calls. In CountWords, the call becomes:

Program.cs (in CountWords)
await context.QueueStateUpdateAsync("sentence", sentence, Scope, cancellationToken);

And in DescribeCount:

Program.cs (in DescribeCount)
string? sentence = await context.ReadStateAsync<string>("sentence", Scope, cancellationToken);

The third argument of each call is now the scope name, stats, and the token follows it in its usual place, so it no longer needs cancellationToken: in front of it. const makes Scope a constant: both steps use one name, written once.

Step 9: Run It Again​

Terminal
dotnet run
Output
Output: "Workflows pass messages between steps" has 5 words.

macOS-style terminal window titled Terminal — SentenceStats showing dotnet run printing Output: followed by the full sentence Workflows pass messages between steps in quotes and has 5 words

DescribeCount read the sentence that CountWords kept, because both steps now name the scope stats. The count still comes in the message, and the sentence comes from the state.

The Complete File​

Program.cs
using Microsoft.Agents.AI.Workflows;

// One scope name for both steps: without it, each step reads and writes a scope of its own.
const string Scope = "stats";

Func<string, IWorkflowContext, CancellationToken, ValueTask<int>> count = async (sentence, context, cancellationToken) =>
{
// Keep the sentence in the workflow's state, so a later step can read it.
await context.QueueStateUpdateAsync("sentence", sentence, Scope, cancellationToken);
return sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
};

Func<int, IWorkflowContext, CancellationToken, ValueTask<string>> describe = async (words, context, cancellationToken) =>
{
// The message brings only the count. The sentence comes from the state.
string? sentence = await context.ReadStateAsync<string>("sentence", Scope, cancellationToken);
return $"\"{sentence}\" has {words} words.";
};

ExecutorBinding countWords = count.BindAsExecutor("CountWords");
ExecutorBinding describeCount = describe.BindAsExecutor("DescribeCount");

Workflow workflow = new WorkflowBuilder(countWords)
.AddEdge(countWords, describeCount)
.WithOutputFrom(describeCount)
.Build();

await using Run run = await InProcessExecution.RunAsync(workflow, "Workflows pass messages between steps");

foreach (WorkflowOutputEvent output in run.OutgoingEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}

macOS-style code window titled Program.cs — SentenceStats showing a constant scope name stats, a CountWords function that keeps the sentence in the workflow's state with QueueStateUpdateAsync in that scope and returns the word count, a DescribeCount function that reads the sentence back with ReadStateAsync from the same scope, the two functions bound as executors and connected by a WorkflowBuilder, and a loop that prints the workflow's output

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the scope name in the step that writes and in the step that readsEach step uses its own private scope, and the reading step gets null: the empty quotes in Step 6Pass the same scope name to both calls
Giving the write and the read different scope namesThey're two different shared scopes, so the reading step finds nothingKeep the name in one constant, such as Scope, and use it in both calls
Reading the value in a step that runs in the same superstep as the step that writes itThe reading step doesn't see the new value yet: other steps see it from the next superstepRead it in a step that runs after the writer, such as one its edge leads to
Using the value without checking it for nullA missing value goes unnoticed. Here it became an empty sentenceCheck for null, as Microsoft's own sample does: it throws when the value isn't there

FAQ​

Can the step that writes a value read it back at once?​

Yes. The State guide: The executor that calls QueueStateUpdateAsync can read the updated value immediately in the same handler. Only the other steps wait for the next superstep.

Why not send the sentence in the message instead?​

You can: a step can return a type of your own that holds both the sentence and the count. State fits when a later step needs a value that the message from the step before it doesn't carry, the case the State guide describes as one where direct message passing is not feasible or efficient.

Is the state saved in a checkpoint?​

Yes. Microsoft's Checkpoints guide says A checkpoint captures the entire state of the workflow, and lists shared states among what it includes, next to the executors' state and the pending messages.

Conclusion​

To share a value between the steps of a Microsoft Agent Framework workflow, write it with QueueStateUpdateAsync in one step and read it with ReadStateAsync in a later one, with the same key and the same scope name. Without a scope name, each step reads and writes a scope private to itself, and the reading step gets null. Other steps see the new value from the next superstep on, which is when a step that an edge leads to runs.

Additional Resources​