前面已经讨论过,Workflow Core的流程与主流程不在同一进程运行,如果我们需要知道流程的运行状态,需要使用OnLifeCycleEvent事件,当流程启动和结束、流程步骤开始和结束时,会触发这个事件。我们可以在这个事件中判断相关流程是否结束。下面是一个简单的例子,说明如何使用这个事件。
using Microsoft.Extensions.DependencyInjection;
using System;
using WorkflowCore.Interface;
using WorkflowCore.Services.DefinitionStorage;
namespace WorkflowCoreFrameworkDSL
{
class Program
{
static void Main(string[] args)
{
IServiceProvider serviceProvider = ConfigureServices();
var loader = serviceProvider.GetService<IDefinitionLoader>();
var json = System.IO.File.ReadAllText("dataflow.json");
loader.LoadDefinition(json, Deserializers.Json);
var host = serviceProvider.GetService<IWorkflowHost>();
host.Start();
var mybmi = new MyBMI
{
Height=1.75M,
Weight=75
};
var workflowid = host.StartWorkflow("BMIFlow", 1, mybmi).Result;
host.OnLifeCycleEvent += (evt) =>
{
if (evt.WorkflowInstanceId == workflowid && evt.ToString() == "WorkflowCore.Models.LifeCycleEvents.WorkflowCompleted")
{
Console.WriteLine(mybmi.Height);
Console.WriteLine(mybmi.Weight);
Console.WriteLine(mybmi.BMI);
Console.WriteLine(mybmi.Status);
}
};
Console.ReadLine();
host.Stop();
}
private static IServiceProvider ConfigureServices()
{
//setup dependency injection
IServiceCollection services = new ServiceCollection();
services.AddLogging();
services.AddWorkflow();
//这是新增加的服务
services.AddWorkflowDSL();
var serviceProvider = services.BuildServiceProvider();
return serviceProvider;
}
}
}
这个例子中有两个步骤,分别计算BMI和判断BMI的状态,采用json文件定义流程:
{
"Id": "BMIFlow",
"Version": 1,
"DataType": "WorkflowCoreFrameworkDSL.MyBMI, WorkflowCoreFrameworkDSL",
"Steps": [
{
"Id": "CalBmi",
"StepType": "WorkflowCoreFrameworkDSL.CalBmi,WorkflowCoreFrameworkDSL",
"NextStepId": "CalStatus",
"Inputs": {
"Height": "data.Height",
"Weight": "data.Weight"
},
"Outputs": {
"BMI": "step.BMI"
}
},
{
"Id": "CalStatus",
"StepType": "WorkflowCoreFrameworkDSL.CalStatus,WorkflowCoreFrameworkDSL",
"Inputs": {
"BMI": "data.BMI"
},
"Outputs": {
"Status": "step.Status"
}
}
]
}
两个Step的代码如下:
using WorkflowCore.Interface;
using WorkflowCore.Models;
namespace WorkflowCoreFrameworkDSL
{
public class CalBmi : StepBody
{
public decimal Height { get; set; }
public decimal Weight { get; set; }
public decimal BMI { get; set; }
public override ExecutionResult Run(IStepExecutionContext context)
{
BMI=Weight/Height/Height;
return ExecutionResult.Next();
}
}
public class CalStatus : StepBody
{
public decimal BMI { get; set; }
public string Status { get; set; }
public override ExecutionResult Run(IStepExecutionContext context)
{
if (BMI < 18) Status = "偏瘦";
else if (BMI < 24) Status = "正常";
else if (BMI < 28) Status = "超重";
else Status = "肥胖";
return ExecutionResult.Next();
}
}
}