如果需要同时执行多个过程相同的而输入不同的流程,可以使用ForEach控制语句,一定要注意,这里的ForEach不是循环,不是一个流程执行完再执行另一个流程,我们仍然使用前面定义的简单的步骤来组织ForEach示例流程,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using ZL.WorflowCoreDemo.InputDataToStep.Steps;
namespace ZL.WorflowCoreDemo.Paralle
{
public class ParalleWorkflow : IWorkflow
{
public string Id => "ParalleWorkflow";
public int Version => 1;
public void Build(IWorkflowBuilder<object> builder)
{
builder
.StartWith(context => { Console.WriteLine("开始"); ExecutionResult.Next(); })
.ForEach(data => new List<string>() { "张三", "李四", "王五", "赵六" })
.Do(x => x
.StartWith<HelloWithName>()
.Input(step => step.Name, (data, context) => context.Item as string)
.Then<GoodbyeWithName>()
.Input(step => step.Name, (data, context) => context.Item as string)
)
.Then(context => { Console.WriteLine("结束"); ExecutionResult.Next(); });
}
}
}
在这个例子里,我们没有定义相关的数据类,需要输入的人名作为ForEach中的循环变量,这些变量保存在context中,输入到相应的环节中。执行代码如下:
IServiceProvider serviceProvider = ConfigureServices();
var host = serviceProvider.GetService<IWorkflowHost>();
host.RegisterWorkflow<ParalleWorkflow>();
host.Start();
host.StartWorkflow("ParalleWorkflow", 1, null);
Console.ReadLine();
host.Stop();
例子的执行效果如下: