Skip to main content

How to Run One Microsoft Agent Framework Workflow for Many Requests at Once in C#

· 14 min read
Jagdish Kumawat
Founder @ Dewiride

An app that builds a Microsoft Agent Framework workflow once, such as a web API, gets many requests for it, often at the same moment. A workflow instance serves several runs at once only when every executor in it is declared shareable or created by a factory, and the runs use InProcessExecution.Concurrent. This guide runs one workflow three times at once both ways, and all three results arrive after 1.04 seconds.

Syntax​

Syntax
// Option 1: one executor instance, declared safe to share between runs
internal sealed partial class <YourExecutor>() : Executor("<id>", declareCrossRunShareable: true)

// Option 2: a factory that creates a new executor for each run
ExecutorBinding <binding> = <factory>.BindExecutor("<id>");

// With either option, start each request's run in the concurrent environment
await using Run <run> = await InProcessExecution.Concurrent.RunAsync(<workflow>, <input>);
PartWhat it is
<YourExecutor>, <id>Your executor class, and its id in the workflow
declareCrossRunShareable: trueThe Executor constructor's third parameter, false by default. Agent Framework's documentation: Declare that this executor may be used simultaneously by multiple runs safely.
<factory>A Func<string, string, ValueTask<TExecutor>> that returns a new executor each time it's called
BindExecutor("<id>")Turns the factory into an ExecutorBinding, a step you build the workflow from, with the id you give it
InProcessExecution.ConcurrentThe execution environment that lets several runs use one workflow instance at the same time
<workflow>, <input>The workflow, built once, and one request's input

Microsoft's page on execution modes sets the rule: Concurrent execution requires that all executors in the workflow be declared crossRunShareable (on the constructor) or be provided as factory methods.

The Example​

A console app called ConcurrentGreetings has a workflow with one step, Greet, which waits one second, as a call to a model or another service would, and returns a greeting. The app builds the workflow once, starts three runs of it at the same moment for Ana, Ben and Chen, and prints how many seconds after the start each greeting arrived. There's no AI model in it, so nothing needs an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0; this guide used 10.0.404.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create a console app, move into it and add Agent Framework's workflows packages:

Terminal
dotnet new console -o ConcurrentGreetings
cd ConcurrentGreetings
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
dotnet add package Microsoft.Agents.AI.Workflows.Generators --version 1.28.0
  • dotnet new console -o ConcurrentGreetings creates a console app in a new ConcurrentGreetings folder, and cd moves into it.
  • Microsoft.Agents.AI.Workflows is Agent Framework's workflows package. --version keeps you on the version this guide used.
  • Microsoft.Agents.AI.Workflows.Generators is its source generator. Microsoft's documentation describes it as the source generator that registers [MessageHandler] methods in partial executor classes, and the executor in this guide is such a class.
Output (shortened)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ConcurrentGreetings/ConcurrentGreetings.csproj:
Restore succeeded.
…
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/ConcurrentGreetings/ConcurrentGreetings.csproj'.
info : Generating MSBuild file /Users/you/source/ConcurrentGreetings/obj/ConcurrentGreetings.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/ConcurrentGreetings/obj/project.assets.json
log : Restored /Users/you/source/ConcurrentGreetings/ConcurrentGreetings.csproj (in 757 ms).
…
info : PackageReference for package 'Microsoft.Agents.AI.Workflows.Generators' version '1.28.0' added to file '/Users/you/source/ConcurrentGreetings/ConcurrentGreetings.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/ConcurrentGreetings/obj/project.assets.json
log : Restored /Users/you/source/ConcurrentGreetings/ConcurrentGreetings.csproj (in 983 ms).

Open ConcurrentGreetings.csproj to see what the two commands added:

ConcurrentGreetings.csproj (the package references)
<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
<PackageReference Include="Microsoft.Agents.AI.Workflows.Generators" Version="1.28.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

The generator's reference got IncludeAssets and PrivateAssets because the package marks itself as a development dependency. Microsoft's documentation explains what that means for your projects: Source generator packages don't flow transitively, so reference it directly in the project that defines the executors.

Step 2: Write the Executor and Start Three Runs at Once​

Replace everything in Program.cs with:

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

GreetExecutor greet = new();
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();

string[] names = ["Ana", "Ben", "Chen"];
Stopwatch stopwatch = Stopwatch.StartNew();

// Three requests arrive at the same time, and all three run the one workflow.
await Task.WhenAll(names.Select(async name =>
{
try
{
await using Run run = await InProcessExecution.RunAsync(workflow, name);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {output.Data}");
}
}
}
catch (Exception exception)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {name}: {exception.GetType().Name}: {exception.Message}");
}
}));

// A step that takes a second, like a call to a model or another service.
internal sealed partial class GreetExecutor() : Executor("Greet")
{
[MessageHandler]
private async ValueTask<string> HandleAsync(string name, IWorkflowContext context, CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
return $"Hello, {name}!";
}
}
  • GreetExecutor is a class-based executor with the id Greet. [MessageHandler] marks HandleAsync as the method that handles a string message: it waits one second and returns the greeting. Writing a class-based executor has a guide of its own.
  • new WorkflowBuilder(greet).WithOutputFrom(greet).Build() builds the workflow once. Greet is its first step, and what Greet returns is the workflow's output.
  • Task.WhenAll(names.Select(...)) starts one run per name, all three at once, and waits until every one has finished.
  • InProcessExecution.RunAsync(workflow, name) runs the workflow with the name as its input. The loop prints the output with the seconds since the start.
  • The catch block prints an exception with the name it belongs to, so a run that fails shows up in the output too.

Run it with dotnet run, and only Ana's run greets her: Ben's and Chen's throw InvalidOperationException: Cannot use a Workflow that is already owned by another runner or parent workflow., because a run started with InProcessExecution.RunAsync owns the workflow until it ends. That error has its own post.

Step 3: Declare the Executor Shareable and Run Concurrently​

Two changes let the three runs share the workflow. First, declare Greet shareable. Replace the comment and the class declaration line with:

Program.cs (the executor)
// A step that takes a second, like a call to a model or another service. It keeps nothing
// in its fields, so one instance can serve several runs at the same time.
internal sealed partial class GreetExecutor() : Executor("Greet", declareCrossRunShareable: true)

declareCrossRunShareable: true tells Agent Framework that one GreetExecutor can serve several runs at the same time. That's true here: HandleAsync uses only the name it receives, and the class keeps nothing in fields.

Second, start each run in the concurrent environment. Replace the RunAsync line with:

Program.cs (the run)
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, name);

Both changes are needed. With InProcessExecution.Concurrent alone, every run fails with Workflow must only consist of cross-run share-capable or factory-created executors., which has its own post too.

Run the app again:

Terminal
dotnet run
Output
1.04 s Hello, Ben!
1.04 s Hello, Ana!
1.04 s Hello, Chen!

macOS-style terminal window titled Terminal — ConcurrentGreetings showing dotnet run with a shareable executor and InProcessExecution.Concurrent: Hello, Ben!, Hello, Ana! and Hello, Chen!, all three printed 1.04 s after the start

All three greetings arrived 1.04 seconds after the start. Each run waits one second, so the three ran at the same time on the one workflow: one after another, they would have needed at least three seconds. They print in the order they finished, Ben's first, although Ana's run started first.

Step 4: Or Create the Executor for Each Run with a Factory​

Declaring an executor shareable is right only when it keeps nothing in fields. An executor that keeps data in fields during a run needs an instance of its own in each run, and a factory gives it one. To try it, take the declaration back to the Step 2 version, without declareCrossRunShareable:

Program.cs (the executor)
// A step that takes a second, like a call to a model or another service.
internal sealed partial class GreetExecutor() : Executor("Greet")

Then replace the two lines at the top that create the executor and build the workflow:

Program.cs (replace)
GreetExecutor greet = new();
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();

with a factory:

Program.cs (new)
// A factory instead of an instance: every run gets its own GreetExecutor.
Func<string, string, ValueTask<GreetExecutor>> createGreet = (_, _) => ValueTask.FromResult(new GreetExecutor());
ExecutorBinding greet = createGreet.BindExecutor("Greet");
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();
  • createGreet is the factory, a function that returns a new GreetExecutor. It receives two strings that this example doesn't need, so (_, _) ignores them.
  • BindExecutor("Greet") turns the factory into the step Greet. Its documentation says the binding resolves to the result of the factory call when messages get sent to it: the workflow holds the factory, not one executor.

The run line stays InProcessExecution.Concurrent.RunAsync. Run the app again:

Terminal
dotnet run
Output
1.04 s Hello, Ben!
1.04 s Hello, Ana!
1.04 s Hello, Chen!

macOS-style terminal window titled Terminal — ConcurrentGreetings showing dotnet run with the executor created by a factory for each run: Hello, Ben!, Hello, Ana! and Hello, Chen!, all three printed 1.04 s after the start

The same 1.04 seconds for all three, with an executor that isn't declared shareable. Microsoft's guide to resettable executors explains why a factory-created executor needs nothing more: Each run gets a new instance with clean state.

Which One to Use​

Your executorUseWhy
Keeps nothing in fieldsdeclareCrossRunShareable: trueOne instance can serve every run at once, as in Step 3
Keeps data in fields during a runA factory with BindExecutorEach run gets an instance of its own, as in Step 4

Microsoft's decision table for resettable executors lists both kinds among the executors that need no reset between runs: one declared cross-run shareable, and one created fresh by a factory method.

The Complete File​

With a Shareable Executor​

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

GreetExecutor greet = new();
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();

string[] names = ["Ana", "Ben", "Chen"];
Stopwatch stopwatch = Stopwatch.StartNew();

// Three requests arrive at the same time, and all three run the one workflow.
await Task.WhenAll(names.Select(async name =>
{
try
{
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, name);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {output.Data}");
}
}
}
catch (Exception exception)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {name}: {exception.GetType().Name}: {exception.Message}");
}
}));

// A step that takes a second, like a call to a model or another service. It keeps nothing
// in its fields, so one instance can serve several runs at the same time.
internal sealed partial class GreetExecutor() : Executor("Greet", declareCrossRunShareable: true)
{
[MessageHandler]
private async ValueTask<string> HandleAsync(string name, IWorkflowContext context, CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
return $"Hello, {name}!";
}
}

macOS-style code window titled Program.cs — ConcurrentGreetings showing one workflow built from a GreetExecutor, three runs for Ana, Ben and Chen started together with Task.WhenAll and InProcessExecution.Concurrent.RunAsync, and the GreetExecutor class declared with declareCrossRunShareable: true, whose handler waits one second and returns a greeting

With a Factory​

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

// A factory instead of an instance: every run gets its own GreetExecutor.
Func<string, string, ValueTask<GreetExecutor>> createGreet = (_, _) => ValueTask.FromResult(new GreetExecutor());
ExecutorBinding greet = createGreet.BindExecutor("Greet");
Workflow workflow = new WorkflowBuilder(greet).WithOutputFrom(greet).Build();

string[] names = ["Ana", "Ben", "Chen"];
Stopwatch stopwatch = Stopwatch.StartNew();

// Three requests arrive at the same time, and all three run the one workflow.
await Task.WhenAll(names.Select(async name =>
{
try
{
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, name);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {output.Data}");
}
}
}
catch (Exception exception)
{
Console.WriteLine($"{stopwatch.Elapsed.TotalSeconds:0.00} s {name}: {exception.GetType().Name}: {exception.Message}");
}
}));

// A step that takes a second, like a call to a model or another service.
internal sealed partial class GreetExecutor() : Executor("Greet")
{
[MessageHandler]
private async ValueTask<string> HandleAsync(string name, IWorkflowContext context, CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
return $"Hello, {name}!";
}
}

Common Mistakes​

MistakeWhat happensDo this instead
Starting simultaneous runs of one workflow with InProcessExecution.RunAsyncThe first run owns the workflow, and the others throw Cannot use a Workflow that is already owned by another runner or parent workflow. (the fix)Use InProcessExecution.Concurrent
Using InProcessExecution.Concurrent with executors left at the defaultEvery run throws Workflow must only consist of cross-run share-capable or factory-created executors. (the fix)Declare every executor shareable, or create it with a factory
Declaring an executor shareable while it keeps data in fieldsEvery run uses the same instance, and with it the same fieldsCreate it with a factory

FAQ​

Why not build a new workflow for every request?​

You can, and Microsoft's documentation recommends it as the default way to keep runs apart: it is recommended to create a new workflow instance from the builder for each task or request to ensure proper state isolation and thread safety. Sharing one workflow, as in this guide, is for when building it once is a deliberate choice, for example when executor construction is expensive.

Does a shareable executor have to be safe for several runs at once?​

Yes, and that's up to your code. The parameter only declares it: Declare that this executor may be used simultaneously by multiple runs safely. Greet qualifies because it keeps nothing in fields.

What about executors made from functions?​

BindAsExecutor, which turns a function into an executor, has a threadsafe parameter for the same purpose. Its documentation: Declare that the message handler may be used simultaneously by multiple runs concurrently.

Conclusion​

One Microsoft Agent Framework workflow can serve many requests at once when every executor in it can be shared. Declare an executor that keeps nothing in fields with declareCrossRunShareable: true, or create one that does with a factory and BindExecutor, then start each run with InProcessExecution.Concurrent.RunAsync. In the example, three one-second runs finished together after 1.04 seconds both ways.

Additional Resources​