Parallel Execution
Overview
Parallel Execution Patterns
1. Parallel Activity
Code Example
using Elsa.Workflows;
using Elsa.Workflows.Activities;
using Elsa.Workflows.Contracts;
namespace MyApp.Workflows;
public class ParallelProcessingWorkflow : WorkflowBase
{
protected override void Build(IWorkflowBuilder builder)
{
builder.Name = "Parallel Processing Example";
var results = builder.WithVariable<List<string>>();
builder.Root = new Sequence
{
Activities =
{
new WriteLine("Starting parallel execution..."),
new Parallel
{
Activities =
{
// Branch 1: Process order validation
new Sequence
{
Activities =
{
new WriteLine("Branch 1: Validating order..."),
new Delay(TimeSpan.FromSeconds(2)),
new WriteLine("Branch 1: Order validated"),
new SetVariable
{
Variable = results,
Value = new(context =>
{
var list = results.Get(context) ?? new List<string>();
list.Add("Order validated");
return list;
})
}
}
},
// Branch 2: Check inventory
new Sequence
{
Activities =
{
new WriteLine("Branch 2: Checking inventory..."),
new Delay(TimeSpan.FromSeconds(1)),
new WriteLine("Branch 2: Inventory checked"),
new SetVariable
{
Variable = results,
Value = new(context =>
{
var list = results.Get(context) ?? new List<string>();
list.Add("Inventory available");
return list;
})
}
}
},
// Branch 3: Calculate shipping
new Sequence
{
Activities =
{
new WriteLine("Branch 3: Calculating shipping..."),
new Delay(TimeSpan.FromSeconds(1.5)),
new WriteLine("Branch 3: Shipping calculated"),
new SetVariable
{
Variable = results,
Value = new(context =>
{
var list = results.Get(context) ?? new List<string>();
list.Add("Shipping calculated");
return list;
})
}
}
}
}
},
new WriteLine(context => $"All parallel tasks completed. Results: {string.Join(", ", results.Get(context) ?? new List<string>())}")
}
};
}
}2. ForEach with Parallel Execution
Code Example
3. Flowchart with Parallel Branches
Designer Workflow
Considerations and Best Practices
Shared Variables and Race Conditions
Problem: Concurrent Writes
Solution: Use Separate Variables or Synchronization
Error Handling in Parallel Branches
Default Behavior
Handling Faults
Performance Considerations
When to Use Parallel Execution
Parallel Execution in Designer vs Code
Designer (Elsa Studio)
Programmatic (Code)
Related Documentation
Summary
Last updated