WF 4 活动工具箱中的示例包括:Sequence、Parallel、If、ForEach、Pick、Flowchart 和 Switch 等等。
WF 控制流是基于层次结构的,因此 WF 程序就是一个活动树。
您将了解如何采用循序渐进的方法编写自己的控制流活动:我们从一个非常简单的控制流活动开始,逐渐丰富其内容,最终打造一个有用的新控制流活动。我们所有示例的源代码都可供下载。
但首先,让我们介绍一些有关活动的基本概念,让大家掌握一些基础知识。
活动
我们称之为叶 活动。
msdn.microsoft.com/library/dd560893。
图 1 活动类型层次结构
控制流活动通常用于安排其他活动(例如 Sequence、Parallel 或 Flowchart),但也可能包含以下活动:使用 CancellationScope 或 Pick 实施自定义取消;使用 Receive 创建书签;使用 Persist 实现持久性。
变量表示数据的临时存储。
活动的创建者使用参数来定义数据在活动中流入和流出的方式,并且按照以下几种方式来使用变量:
- 在活动定义上公开一个用户可编辑的变量集,以便在多个活动中共享变量(例如 Sequence 和 Flowchart 中的 Variables 集合)。
- 为活动的内部状态建模。
将变量和参数结合使用,可以为活动之间的通信提供可预测的通信模式。
现在,我已经介绍了活动的一些核心基础知识,接下来让我们开始第一个控制流活动。
一个简单的控制流活动
对于这种情况,我们需要一个活动,该活动能够根据布尔条件的值执行另一个活动。
此活动的工作原理应该是这样的:
- 这个参数是必需参数。
- 活动用户可以提供主体,即在条件为 True 时执行的活动。
- 在执行时:如果条件为 True 且主体不为 Null,则执行主体。
下面是一个 ExecuteIfTrue 活动的实现,其行为方式与上文所述完全相同:
public class ExecuteIfTrue : NativeActivity { [RequiredArgument] public InArgument<bool> Condition { get; set; } public Activity Body { get; set; } public ExecuteIfTrue() { } protected override void Execute(NativeActivityContext context) { if (context.GetValue(this.Condition) && this.Body != null) context.ScheduleActivity(this.Body); } }
因此,它必须从 NativeActivity 派生,因为它需要与 WF 运行时交互以安排子活动。
WF 运行时将在准备要执行的活动时强制进行此项验证:
- [RequiredArgument]
- public InArgument<bool> Condition { get; set; }
- public Activity Body { get; set; }
WF 运行时不会立即执行活动,而是将这些活动添加到一个工作项列表中以安排执行:
- protected override void Execute(NativeActivityContext context)
- {
- if (context.GetValue(this.Condition) && this.Body != null)
- context.ScheduleActivity(this.Body);
- }
这意味着该类型便于进行 XAML 序列化。
在本例中,如果当前日期为星期六,则将向控制台输出字符串“Rest!”:
- var act = new ExecuteIfTrue
- {
- Condition = new InArgument<bool>(c => DateTime.Now.DayOfWeek == DayOfWeek.Tuesday),
- Body = new WriteLine { Text = "Rest!" }
- };
- WorkflowInvoker.Invoke(act);
但是不要被该代码的简单性所迷惑,它实际上是一个功能完备的控制流活动!
安排多个子活动
此活动在功能上与产品附带的 Sequence 几乎完全相同。
此活动的工作原理应该是这样的:
- 活动的用户必须通过 Activities 属性提供要按顺序执行的子活动集合。
-
在执行时:
- 活动包含一个内部变量,其值是已经执行的集合中最后一项的索引。
- 如果子活动集合中包含内容,则安排第一个子活动。
-
当子活动完成时:
- 递增最后执行的项的索引。
- 如果索引仍在子活动集合的范围内,则安排下一个子活动。
- 重复执行。
图 2 中的代码实现了一个 SimpleSequence 活动,其行为方式与上文所述完全相同。
图 2 SimpleSequence 活动
- public class SimpleSequence : NativeActivity
- {
- // Child activities collection
- Collection<Activity> activities;
- Collection<Variable> variables;
- // Pointer to the current item in the collection being executed
- Variable<int> current = new Variable<int>() { Default = 0 };
- public SimpleSequence() { }
- // Collection of children to be executed sequentially by SimpleSequence
- public Collection<Activity> Activities
- {
- get
- {
- if (this.activities == null)
- this.activities = new Collection<Activity>();
- return this.activities;
- }
- }
- public Collection<Variable> Variables
- {
- get
- {
- if (this.variables == null)
- this.variables = new Collection<Variable>();
- return this.variables;
- }
- }
- protected override void CacheMetadata(NativeActivityMetadata metadata)
- {
- metadata.SetChildrenCollection(this.activities);
- metadata.SetVariablesCollection(this.variables);
- metadata.AddImplementationVariable(this.current);
- }
- protected override void Execute(NativeActivityContext context)
- {
- // Schedule the first activity
- if (this.Activities.Count > 0)
- context.ScheduleActivity(this.Activities[0], this.OnChildCompleted);
- }
- void OnChildCompleted(NativeActivityContext context, ActivityInstance completed)
- {
- // Calculate the index of the next activity to scheduled
- int currentExecutingActivity = this.current.Get(context);
- int next = currentExecutingActivity + 1;
- // If index within boundaries...
- if (next < this.Activities.Count)
- {
- // Schedule the next activity
- context.ScheduleActivity(this.Activities[next], this.OnChildCompleted);
- // Store the index in the collection of the activity executing
- this.current.Set(context, next);
- }
- }
- }
代码很简单,但引入了一些有趣的概念。
因此,它从 NativeActivity 派生,因为它需要与运行时交互以安排子活动。
因此,这些属性符合“创建-设置-使用”模式。
图 3 延迟实例化方法
- public Collection<Activity> Activities
- {
- get
- {
- if (this.activities == null)
- this.activities = new Collection<Activity>();
- return this.activities;
- }
- }
- public Collection<Variable> Variables
- {
- get
- {
- if (this.variables == null)
- this.variables = new Collection<Variable>();
- return this.variables;
- }
- }
类中有一个私有成员,不属于签名:名为“current”的 Variable<int> 用于保存正在执行的活动的索引:
- // Pointer to the current item in the collection being executed
- Variable<int> current = new Variable<int>() { Default = 0 };
此目的通过使用 ImplementationVariable 来实现。
为了清楚地说明这一点,并继续 Sequence 示例:如果保存了 SimpleSequence 实例,当它复原时,将“记住”执行过的最后一个活动的索引。
此项活动在 CacheMetadata 方法的执行过程中进行。
在 CacheMetadata 中,此活动会说:“大家好,我是 If 活动,我有一个输入变量叫 Condition,还有两个子活动,分别是 Then 和 Else。”当使用 SimpleSequence 活动时,此活动会说:“大家好,我是 SimpleSequence,我有一个子活动集合、一个变量集合和一个实现变量。”CacheMetadata 代码中包含的内容也无非就是 SimpleSequence 代码中的那些内容:
- protected override void CacheMetadata(NativeActivityMetadata metadata)
- {
- metadata.SetChildrenCollection(this.activities);
- metadata.SetVariablesCollection(this.variables);
- metadata.AddImplementationVariable(this.current);
- }
而 SimpleSequence 则相反,因为默认实现“猜不出”我要使用实现变量,所以必须实现此活动。
安排活动时不会调用 CompletionCallback,安排的活动执行完成时才会调用 CompletionCallback:
- protected override void Execute(NativeActivityContext context)
- {
- // Schedule the first activity
- if (this.Activities.Count > 0)
- context.ScheduleActivity(this.Activities[0], this.OnChildCompleted);
- }
了解如何为多个执行波编程是成为一个熟练的控制流活动创建者的最大挑战之一:
- void OnChildCompleted(NativeActivityContext context, ActivityInstance completed)
- {
- // Calculate the index of the next activity to scheduled
- int currentExecutingActivity = this.current.Get(context);
- int next = currentExecutingActivity + 1;
- // If index within boundaries...
- if (next < this.Activities.Count)
- {
- // Schedule the next activity
- context.ScheduleActivity(this.Activities[next], this.OnChildCompleted);
- // Store the index in the collection of the activity executing
- this.current.Set(context, next);
- }
- }
在本示例中,我要将三个字符串写入控制台(“Hello”、“Workflow”和“!”):
- var act = new SimpleSequence()
- {
- Activities =
- {
- new WriteLine { Text = "Hello" },
- new WriteLine { Text = "Workflow" },
- new WriteLine { Text = "!" }
- }
- };
- WorkflowInvoker.Invoke(act);
现在,让我们迎接下一个挑战。
实现新的控制流模式
本节将介绍如何构建您自己的控制流活动,以支持 WF 4 自带的现成控制流模式以外的模式。
目标很简单:提供支持 GoTo 的 Sequence,通过工作流内部(通过 GoTo 活动)或通过主机(通过恢复众所周知的书签)显式操作下一个要执行的活动。
为了实现这个新的控制流,我需要创建两个活动:Series,一个复合活动,包含活动集合并按顺序执行其中的活动(但允许跳转至序列中的任一项);GoTo,一个叶活动,我将在 Series 内部使用此活动显式建立跳转模型。
总的来说,我将一一列举自定义控制活动的目标和要求:
- 它是一个活动 Sequence。
- 它可以包含 GoTo 活动(在任何深度),用于将执行点更改至 Series 的任一直接子活动。
- 也可以从外部(例如,从一个用户)接收 GoTo 消息,将执行点更改至 Series 的任一直接子活动。
让我们用简单的语言来描述执行语义:
- 活动的用户必须通过 Activities 属性提供要按顺序执行的子活动集合。
-
在执行方法中:
- 用子活动可以使用的方法为 GoTo 创建一个书签。
- 活动包含一个内部变量,其值是正在执行的活动实例。
- 如果子活动集合中包含内容,则安排第一个子活动。
-
当子活动完成时:
- 在 Activities 集合中查找已完成的活动。
- 递增最后执行的项的索引。
- 如果索引仍在子活动集合的范围内,则安排下一个子活动。
- 重复执行。
-
如果已恢复 GoTo 书签:
- 获取我们要转到的活动的名称。
- 在活动集合中找到该活动。
- 将目标活动安排在执行集中,然后注册一个完成回调,以安排下一个活动。
- 取消当前正在执行的活动。
- 将当前正在执行的活动存储到“current”变量中。
图 4 中的代码示例显示了 Series 活动的实现,其行为方式与上文所述完全相同。
图 4 Series 活动
- public class Series : NativeActivity
- {
- internal static readonly string GotoPropertyName =
- "Microsoft.Samples.CustomControlFlow.Series.Goto";
- // Child activities and variables collections
- Collection<Activity> activities;
- Collection<Variable> variables;
- // Activity instance that is currently being executed
- Variable<ActivityInstance> current = new Variable<ActivityInstance>();
- // For externally initiated goto's; optional
- public InArgument<string> BookmarkName { get; set; }
- public Series() { }
- public Collection<Activity> Activities
- {
- get {
- if (this.activities == null)
- this.activities = new Collection<Activity>();
- return this.activities;
- }
- }
- public Collection<Variable> Variables
- {
- get {
- if (this.variables == null)
- this.variables = new Collection<Variable>();
- return this.variables;
- }
- }
- protected override void CacheMetadata(NativeActivityMetadata metadata)
- {
- metadata.SetVariablesCollection(this.Variables);
- metadata.SetChildrenCollection(this.Activities);
- metadata.AddImplementationVariable(this.current);
- metadata.AddArgument(new RuntimeArgument("BookmarkName", typeof(string),
- ArgumentDirection.In));
- }
- protected override bool CanInduceIdle { get { return true; } }
- protected override void Execute(NativeActivityContext context)
- {
- // If there activities in the collection...
- if (this.Activities.Count > 0)
- {
- // Create a bookmark for signaling the GoTo
- Bookmark internalBookmark = context.CreateBookmark(this.Goto,
- BookmarkOptions.MultipleResume | BookmarkOptions.NonBlocking);
- // Save the name of the bookmark as an execution property
- context.Properties.Add(GotoPropertyName, internalBookmark);
- // Schedule the first item in the list and save the resulting
- // ActivityInstance in the "current" implementation variable
- this.current.Set(context, context.ScheduleActivity(this.Activities[0],
- this.OnChildCompleted));
- // Create a bookmark for external (host) resumption
- if (this.BookmarkName.Get(context) != null)
- context.CreateBookmark(this.BookmarkName.Get(context), this.Goto,
- BookmarkOptions.MultipleResume | BookmarkOptions.NonBlocking);
- }
- }
- void Goto(NativeActivityContext context, Bookmark b, object obj)
- {
- // Get the name of the activity to go to
- string targetActivityName = obj as string;
- // Find the activity to go to in the children list
- Activity targetActivity = this.Activities
- .Where<Activity>(a =>
- a.DisplayName.Equals(targetActivityName))
- .Single();
- // Schedule the activity
- ActivityInstance instance = context.ScheduleActivity(targetActivity,
- this.OnChildCompleted);
- // Cancel the activity that is currently executing
- context.CancelChild(this.current.Get(context));
- // Set the activity that is executing now as the current
- this.current.Set(context, instance);
- }
- void OnChildCompleted(NativeActivityContext context, ActivityInstance completed)
- {
- // This callback also executes when cancelled child activities complete
- if (completed.State == ActivityInstanceState.Closed)
- {
- // Find the next activity and execute it
- int completedActivityIndex = this.Activities.IndexOf(completed.Activity);
- int next = completedActivityIndex + 1;
- if (next < this.Activities.Count)
- this.current.Set(context,
- context.ScheduleActivity(this.Activities[next],
- this.OnChildCompleted));
- }
- }
- }
我将讨论此活动的实现。
Series 从 NativeActivity 派生,因为它需要与 WF 运行时交互以安排子活动、创建书签、取消子活动以及使用执行属性。
同样,我将按照“创建-设置-使用”模式设计活动类型。
我稍后会解释具体细节,现在最重要的是要了解,会有一个用于保存正在执行的活动实例的实现变量:
- Variable<ActivityInstance> current = new Variable<ActivityInstance>();
与前一个示例的唯一区别是,我会手动在 WF 运行时中注册 BookmarkName 输入参数,将新的 RuntimeArgument 实例添加到活动元数据中:
- protected override void CacheMetadata(NativeActivityMetadata metadata)
- {
- metadata.SetVariablesCollection(this.Variables);
- metadata.SetChildrenCollection(this.Activities);
- metadata.AddImplementationVariable(this.current);
- metadata.AddArgument(new RuntimeArgument("BookmarkName",
- typeof(string), ArgumentDirection.In));
- }
如果此属性返回 False,并且我们创建了一个书签,我会在执行活动时收到 InvalidOperationException 异常:
- protected override bool CanInduceIdle { get { return true; } }
但是,在进行下一步之前,让我先介绍一下书签和执行属性。
在您使用书签时,可以利用某种响应执行的形式创建自己的活动:创建书签就会生成活动,恢复书签就会调用一段代码(书签恢复回调),以响应书签的恢复。
因此,活动能够通过这些属性将数据与其后代共享。
以下是最佳做法:
- internal static readonly string GotoPropertyName =
- "Microsoft.Samples.CustomControlFlow.Series.Goto";
- ...
- ...
- // Create a bookmark for signaling the GoTo
- Bookmark internalBookmark = context.CreateBookmark(this.Goto,
- BookmarkOptions.MultipleResume | BookmarkOptions.NonBlocking);
- // Save the name of the bookmark as an execution property
- context.Properties.Add(GotoPropertyName, internalBookmark);
同一个活动可以有多个 ActivityInstance:
- // Schedule the first item in the list and save the resulting
- // ActivityInstance in the "current" implementation variable
- this.current.Set(context, context.ScheduleActivity(this.Activities[0],
- this.OnChildCompleted));
其中的原理很简单:因为主机知道书签的名称,所以它可以通过跳转到 Series 中的任一活动来恢复该书签:
- // Create a bookmark for external (host) resumption
- if (this.BookmarkName.Get(context) != null)
- context.CreateBookmark(this.BookmarkName.Get(context), this.Goto,
- BookmarkOptions.MultipleResume | BookmarkOptions.NonBlocking);
主要的区别是,只有在当前活动成功完成执行(即到达关闭状态,未被取消或出错)时,我才会安排下一个活动。
在本例中,该数据是我们要转到的活动的名称:
- void Goto(NativeActivityContext context, Bookmark b, object data)
- {
- // Get the name of the activity to go to
- string targetActivityName = data as string;
- ...
- }
找到请求的活动后,就对其进行安排,指明活动完成后就应当执行 OnChildCompleted 方法:
- // Find the activity to go to in the children list
- Activity targetActivity = this.Activities
- .Where<Activity>(a =>
- a.DisplayName.Equals(targetActivityName))
- .Single();
- // Schedule the activity
- ActivityInstance instance = context.ScheduleActivity(targetActivity,
- this.OnChildCompleted);
首先,将此变量作为 NativeActivityContext 的 CancelChild 方法的参数传递,然后使用前面的代码块中安排的 ActivityInstance 来更新变量的值:
- // Cancel the activity that is currently executing
- context.CancelChild(this.current.Get(context));
- // Set the activity that is executing now as the current
- this.current.Set(context, instance);
GoTo 活动
当书签恢复后,Series 就会跳转到所指的活动。
让我们用简单的语言来描述执行语义:
- 这个参数是必需参数。
-
在执行时:
- GoTo 活动会找到 Series 活动创建的“GoTo”书签。
- 如果找到了书签,就通过传递 TargetActivityName,恢复该书签。
-
它将创建一个同步书签,因此活动不会完成。
- 它将由 Series 取消。
图 5 中的代码显示了 GoTo 活动的实现,其行为方式与上文所述完全相同。
图 5 GoTo 活动
- public class GoTo : NativeActivity
- {
- public GoTo()
- { }
- [RequiredArgument]
- public InArgument<string> TargetActivityName { get; set; }
- protected override bool CanInduceIdle { get { return true; } }
- protected override void Execute(NativeActivityContext context)
- {
- // Get the bookmark created by the parent Series
- Bookmark bookmark = context.Properties.Find(Series.GotoPropertyName) as Bookmark;
- // Resume the bookmark passing the target activity name
- context.ResumeBookmark(bookmark, this.TargetActivityName.Get(context));
- // Create a bookmark to leave this activity idle waiting when it does
- // not have any further work to do.
- Series will cancel this activity
- // in its GoTo method
- context.CreateBookmark("SyncBookmark");
- }
- }
我用 RequiredArgument 特性修饰此参数,表示 WF 验证服务将会强制其使用一个表达式。
我依赖默认的 CacheMetadata 实现来反射活动的公共接口,以查找并注册运行时元数据。
该方法将在集合中查找下一个活动,安排该活动并取消当前正在执行的活动:
- // Get the bookmark created by the parent Series
- Bookmark bookmark = context.Properties.Find(Series.GotoPropertyName) as Bookmark;
- // Resume the bookmark passing the target activity name
- context.ResumeBookmark(bookmark, this.TargetActivityName.Get(context));
在本例中,Series.Goto 实际上会取消正在等待该书签恢复的 Goto 活动实例。
如果取消了 GoTo,Series.OnChildCompleted 回调将不执行任何操作,因为只有当完成状态为 Closed(在本例中为 Cancelled)时,它才会安排下一个活动:
- // Create a bookmark to leave this activity idle waiting when it does
- // not have any further work to do.
- Series will cancel this activity
- // in its GoTo method
- context.CreateBookmark("SyncBookmark");
下面是一个简单的示例,用于说明 Series 的基本使用方法,但是此活动还可用于实现复杂的实际业务方案,以帮助您在连续的过程中跳过、重做或跳转至某些步骤。
图 6 在 Series 中使用 GoTo
- var counter = new Variable<int>();
- var act = new Series
- {
- Variables = { counter},
- Activities =
- {
- new WriteLine
- {
- DisplayName = "Start",
- Text = "Step 1"
- },
- new WriteLine
- {
- DisplayName = "First Step",
- Text = "Step 2"
- },
- new Assign<int>
- {
- To = counter,
- Value = new InArgument<int>(c => counter.Get(c) + 1)
- },
- new If
- {
- Condition = new InArgument<bool>(c => counter.Get(c) == 3),
- Then = new WriteLine
- {
- Text = "Step 3"
- },
- Else = new GoTo { TargetActivityName = "First Step" }
- },
- new WriteLine
- {
- Text = "The end!"
- }
- }
- };
- WorkflowInvoker.Invoke(act);
参考
msdn.microsoft.com/netframework/aa663328
channel9.msdn.com/shows/Endpoint/endpointtv-Workflow-and-Custom-Activities-Best-Practices-Part-1/
msdn.microsoft.com/library/dd489425
msdn.microsoft.com/library/system.activities.activityinstance
msdn.microsoft.com/library/dd454495
遵循流程
编写自己的自定义活动时,您可以在 WF 中表现出任何控制流模式,并调整 WF 以适应您的问题的特殊之处。
Leon Welicki 是 Microsoft Windows Workflow Foundation (WF) 团队的一名项目经理,从事 WF 运行时方面的工作。在加入 Microsoft 之前,他曾担任西班牙一家大型电信公司的首席架构师兼开发经理,并且是西班牙马德里萨拉曼卡宗座大学计算机科学研究生学院的外聘副教授。
衷心感谢以下技术专家对本文的审阅:Joe Clancy、Dan Glick、Rajesh Sampath、Bob Schmidt 和 Isaac Yuen