Windows Workflow Foundation (WF) 的主要功能之一是保留和卸载到数据库的空闲工作流运行时的功能。 中的步骤如何:运行工作流演示工作流承载的控制台应用程序的基础知识。 示例演示了启动工作流、工作流生命周期处理程序和恢复书签。 为了有效演示工作流持久性,需要一个支持启动和恢复多个工作流实例的更为复杂的工作流主机。 教程中此步骤演示了如何创建 Windows 窗体主机应用程序,此 Windows 窗体主机应用程序支持启动和恢复多个工作流实例、工作流持久性,并为高级功能(如在后续教程步骤中演示的跟踪和版本控制)提供基础。
Note: 此教程步骤和后续步骤使用中的所有三个工作流类型如何:创建工作流。 如果未完成所有三种类型可以下载完整的版本中的步骤Windows Workflow Foundation (WF45)-入门教程。
Note: 若要下载完整的版本或观看教程视频演练,请参阅Windows Workflow Foundation (WF45)-入门教程。
在本主题中
若要创建持久性数据库
-
打开 SQL Server Management Studio 并连接到本地服务器,例如 。 \SQLEXPRESS。 右键单击数据库节点,本地服务器,然后选择新数据库。 新数据库命名WF45GettingStartedTutorial,接受所有其他值,然后选择确定。
NOTE 请确保已Create Database本地服务器上创建数据库前的权限。
-
选择开放,文件从文件菜单。 浏览到以下文件夹:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\sql\en选择以下两个文件,然后单击打开。
-
SqlWorkflowInstanceStoreLogic.sql
-
SqlWorkflowInstanceStoreSchema.sql
-
-
选择SqlWorkflowInstanceStoreSchema.sql从窗口菜单。 絋粄WF45GettingStartedTutorial中选择可用数据库下拉列表中,选择Execute从查询菜单。
-
选择SqlWorkflowInstanceStoreLogic.sql从窗口菜单。 絋粄WF45GettingStartedTutorial中选择可用数据库下拉列表中,选择Execute从查询菜单。
WARNING 请务必按正确顺序执行前面两个步骤。 如果不按顺序执行查询,系统会发生错误,并且持久性数据库会配置不正确。
若要添加对 DurableInstancing 程序集的引用
-
右键单击NumberGuessWorkflowHost中解决方案资源管理器,然后选择添加引用。
-
选择程序集从添加引用列表中,然后键入
DurableInstancing到搜索程序集框。 这将筛选程序集,使您更易于选择所需引用。 -
旁边的复选框System.Activities.DurableInstancing并System.Runtime.DurableInstancing从搜索结果列表,然后单击确定。
若要创建工作流主机窗体
Note: 此过程中的步骤描述了如何手动添加和配置窗体。 如果需要,您可以下载教程的解决方案文件并将完成后的窗体添加到项目。 若要下载教程文件,请参阅Windows Workflow Foundation (WF45)-入门教程。 一旦下载文件,右键单击NumberGuessWorkflowHost ,然后选择添加引用。 添加对的引用System.Windows.Forms并System.Drawing。 如果添加新的窗体中,将自动添加这些引用外,新项菜单中,但导入窗体时必须手动添加。 添加引用后,右键单击NumberGuessWorkflowHost中解决方案资源管理器,然后选择添加,现有项。 浏览到
Form文件夹中的项目文件,选择WorkflowHostForm.cs (或WorkflowHostForm.vb),然后单击添加。 如果您选择导入窗体,则可以跳到下一节若要添加的属性和帮助器方法的窗体。
-
右键单击NumberGuessWorkflowHost中解决方案资源管理器,然后选择添加,新项。
-
在中已安装模板列表中,选择Windows 窗体,类型
WorkflowHostForm中名称框中,然后单击添加。 -
在窗体上配置以下属性。
属性 值 FormBorderStyle FixedSingle MaximizeBox False 大小 400, 420 -
按照指定顺序将以下控件添加到窗体,并根据指示配置这些属性。
控件 属性:值 Button 姓名:NewGame 位置:13, 13 字号:75, 23 文本:新游戏 标签 位置:94, 18 文本:猜测一个数字,从 1 到 组合框 姓名:NumberRange DropDownStyle:DropDownList 项:10, 100, 1000 位置:228, 12 字号:143, 21 标签 位置:13, 43 文本:工作流类型 组合框 姓名:WorkflowType DropDownStyle:DropDownList 项:StateMachineNumberGuessWorkflow,FlowchartNumberGuessWorkflow,SequentialNumberGuessWorkflow 位置:94, 40 字号:277, 21 标签 姓名:WorkflowVersion 位置:13, 362 文本:工作流版本 GroupBox 位置:13, 67 字号:358, 287 文本:游戏 NOTE 在添加以下控件时,请将其放入 GroupBox。
控件 属性:值 标签 位置:7, 20 文本:工作流实例 ID 组合框 姓名:InstanceId DropDownStyle:DropDownList 位置:121, 17 字号:227, 21 标签 位置:7, 47 文本:猜测 文本框 姓名:猜测 位置:50, 44 字号:65, 20 Button 姓名:EnterGuess 位置:121, 42 字号:75, 23 文本:输入猜测 Button 姓名:QuitGame 位置:274, 42 字号:75, 23 文本:退出 文本框 姓名:WorkflowStatus 位置:10, 73 多行:True 只读:True 滚动条:垂直 字号:338, 208 -
设置AcceptButton到窗体的属性EnterGuess。
以下示例展示了完成的窗体。
Windows Workflow Foundation 工作流主机窗体的屏幕截图。
若要添加的属性和帮助器方法的窗体
本节的步骤将属性和帮助器添加至窗体类,此窗体类将配置窗体的 UI,以支持运行和恢复数字猜测工作流。
-
右键单击WorkflowHostForm中解决方案资源管理器,然后选择查看代码。
-
在包含其他
using(或Imports)语句的文件的顶部添加以下using(或Imports)语句。Imports System.Windows.Forms Imports System.Activities.DurableInstancing Imports System.Activities Imports System.Data.SqlClient Imports System.IOusing System.Windows.Forms; using System.Activities.DurableInstancing; using System.Activities; using System.Data.SqlClient; using System.IO; -
添加到以下成员声明WorkflowHostForm类。
Const connectionString = "Server=.\SQLEXPRESS;Initial Catalog=WF45GettingStartedTutorial;Integrated Security=SSPI" Dim store As SqlWorkflowInstanceStore Dim WorkflowStarting As Booleanconst string connectionString = "Server=.\\SQLEXPRESS;Initial Catalog=WF45GettingStartedTutorial;Integrated Security=SSPI"; SqlWorkflowInstanceStore store; bool WorkflowStarting;NOTE 如果您的连接字符串不同,请更新
connectionString引用数据库。 -
将
WorkflowInstanceId属性添加到WorkflowFormHost类中。Public ReadOnly Property WorkflowInstanceId() As Guid Get If InstanceId.SelectedIndex = -1 Then Return Guid.Empty Else Return New Guid(InstanceId.SelectedItem.ToString()) End If End Get End Propertypublic Guid WorkflowInstanceId { get { return InstanceId.SelectedIndex == -1 ? Guid.Empty : (Guid)InstanceId.SelectedItem; } }InstanceId组合框显示的持久化工作流实例 id 的列表和WorkflowInstanceId属性返回当前所选的工作流。 -
为窗体
Load事件添加处理程序。 若要添加处理程序,请切换到设计视图窗体中,单击事件顶部的图标属性窗口中,然后双击负载.Private Sub WorkflowHostForm_Load(sender As Object, e As EventArgs) Handles Me.Load End Subprivate void WorkflowHostForm_Load(object sender, EventArgs e) { } -
将下列代码添加到
WorkflowHostForm_Load。'Initialize the store and configure it so that it can be used for 'multiple WorkflowApplication instances. store = New SqlWorkflowInstanceStore(connectionString) WorkflowApplication.CreateDefaultInstanceOwner(store, Nothing, WorkflowIdentityFilter.Any) 'Set default ComboBox selections. NumberRange.SelectedIndex = 0 WorkflowType.SelectedIndex = 0 ListPersistedWorkflows()// Initialize the store and configure it so that it can be used for // multiple WorkflowApplication instances. store = new SqlWorkflowInstanceStore(connectionString); WorkflowApplication.CreateDefaultInstanceOwner(store, null, WorkflowIdentityFilter.Any); // Set default ComboBox selections. NumberRange.SelectedIndex = 0; WorkflowType.SelectedIndex = 0; ListPersistedWorkflows();窗体加载时,将配置
SqlWorkflowInstanceStore,范围和工作流类型组合框将设置为默认值,持久性工作流实例将添加到InstanceId组合框。 -
为
SelectedIndexChanged添加InstanceId处理程序。 若要添加处理程序,请切换到设计视图窗体中,选择InstanceId组合框中,单击事件顶部的图标属性窗口中,并双击SelectedIndexChanged。Private Sub InstanceId_SelectedIndexChanged(sender As Object, e As EventArgs) Handles InstanceId.SelectedIndexChanged End Subprivate void InstanceId_SelectedIndexChanged(object sender, EventArgs e) { } -
将下列代码添加到
InstanceId_SelectedIndexChanged。 只要用户使用组合框选择一个工作流,此处理程序就会更新状态窗口。If InstanceId.SelectedIndex = -1 Then Return End If 'Clear the status window. WorkflowStatus.Clear() 'Get the workflow version and display it. 'If the workflow is just starting then this info will not 'be available in the persistence store so do not try and retrieve it. If Not WorkflowStarting Then Dim instance As WorkflowApplicationInstance = _ WorkflowApplication.GetInstance(WorkflowInstanceId, store) WorkflowVersion.Text = _ WorkflowVersionMap.GetIdentityDescription(instance.DefinitionIdentity) 'Unload the instance. instance.Abandon() End Ifif (InstanceId.SelectedIndex == -1) { return; } // Clear the status window. WorkflowStatus.Clear(); // Get the workflow version and display it. // If the workflow is just starting then this info will not // be available in the persistence store so do not try and retrieve it. if (!WorkflowStarting) { WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(this.WorkflowInstanceId, store); WorkflowVersion.Text = WorkflowVersionMap.GetIdentityDescription(instance.DefinitionIdentity); // Unload the instance. instance.Abandon(); } -
将下面的
ListPersistedWorkflows方法添加到窗体类中。Private Sub ListPersistedWorkflows() Using localCon As New SqlConnection(connectionString) Dim localCmd As String = _ "Select [InstanceId] from [System.Activities.DurableInstancing].[Instances] Order By [CreationTime]" Dim cmd As SqlCommand = localCon.CreateCommand() cmd.CommandText = localCmd localCon.Open() Using reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While (reader.Read()) 'Get the InstanceId of the persisted Workflow. Dim id As Guid = Guid.Parse(reader(0).ToString()) InstanceId.Items.Add(id) End While End Using End Using End Subusing (SqlConnection localCon = new SqlConnection(connectionString)) { string localCmd = "Select [InstanceId] from [System.Activities.DurableInstancing].[Instances] Order By [CreationTime]"; SqlCommand cmd = localCon.CreateCommand(); cmd.CommandText = localCmd; localCon.Open(); using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { // Get the InstanceId of the persisted Workflow Guid id = Guid.Parse(reader[0].ToString()); InstanceId.Items.Add(id); } } }ListPersistedWorkflows查询持久性工作流实例的实例存储,并将实例 ID 添加到cboInstanceId组合框。 -
将下面的
UpdateStatus方法和对应的委托添加到窗体类中。 此方法使用当前正在运行的工作流的状态来更新窗体上的状态窗口。Private Delegate Sub UpdateStatusDelegate(msg As String) Public Sub UpdateStatus(msg As String) 'We may be on a different thread so we need to 'make this call using BeginInvoke. If InvokeRequired Then BeginInvoke(New UpdateStatusDelegate(AddressOf UpdateStatus), msg) Else If Not msg.EndsWith(vbCrLf) Then msg = msg & vbCrLf End If WorkflowStatus.AppendText(msg) 'Ensure that the newly added status is visible. WorkflowStatus.SelectionStart = WorkflowStatus.Text.Length WorkflowStatus.ScrollToCaret() End If End Subprivate delegate void UpdateStatusDelegate(string msg); public void UpdateStatus(string msg) { // We may be on a different thread so we need to // make this call using BeginInvoke. if (InvokeRequired) { BeginInvoke(new UpdateStatusDelegate(UpdateStatus), msg); } else { if (!msg.EndsWith("\r\n")) { msg += "\r\n"; } WorkflowStatus.AppendText(msg); WorkflowStatus.SelectionStart = WorkflowStatus.Text.Length; WorkflowStatus.ScrollToCaret(); } } -
将下面的
GameOver方法和对应的委托添加到窗体类中。 工作流完成后,此方法更新窗体用户界面通过删除已完成的工作流的实例 id 从InstanceId组合框。Private Delegate Sub GameOverDelegate() Private Sub GameOver() If InvokeRequired Then BeginInvoke(New GameOverDelegate(AddressOf GameOver)) Else 'Remove this instance from the InstanceId combo box. InstanceId.Items.Remove(InstanceId.SelectedItem) InstanceId.SelectedIndex = -1 End If End Subprivate delegate void GameOverDelegate(); private void GameOver() { if (InvokeRequired) { BeginInvoke(new GameOverDelegate(GameOver)); } else { // Remove this instance from the combo box InstanceId.Items.Remove(InstanceId.SelectedItem); InstanceId.SelectedIndex = -1; } }
若要配置实例存储、 工作流生命周期处理程序和扩展
-
向窗体类添加
ConfigureWorkflowApplication方法。Private Sub ConfigureWorkflowApplication(wfApp As WorkflowApplication) End Subprivate void ConfigureWorkflowApplication(WorkflowApplication wfApp) { }此方法配置
WorkflowApplication、添加所需扩展并添加工作流生命周期事件的处理程序。 -
在
ConfigureWorkflowApplication中,指定SqlWorkflowInstanceStore的WorkflowApplication。'Configure the persistence store. wfApp.InstanceStore = store// Configure the persistence store. wfApp.InstanceStore = store; -
接下来,创建一个
StringWriter实例,并将它添加到Extensions的WorkflowApplication集合中。 当StringWriter添加到扩展它会捕获所有WriteLine活动输出。 当工作流进入空闲状态时,WriteLine输出可从StringWriter提取并显示在窗体上。'Add a StringWriter to the extensions. This captures the output 'from the WriteLine activities so we can display it in the form. Dim sw As New StringWriter() wfApp.Extensions.Add(sw)// Add a StringWriter to the extensions. This captures the output // from the WriteLine activities so we can display it in the form. StringWriter sw = new StringWriter(); wfApp.Extensions.Add(sw); -
为
Completed事件添加以下处理程序。 在工作流成功完成时,执行猜测数字的轮数会显示到状态窗口。 如果工作流终止,系统会显示导致终止的异常信息。 在处理程序结尾处调用了GameOver方法,该方法从工作流列表中删除已完成的工作流。wfApp.Completed = _ Sub(e As WorkflowApplicationCompletedEventArgs) If e.CompletionState = ActivityInstanceState.Faulted Then UpdateStatus(String.Format("Workflow Terminated. Exception: {0}" & vbCrLf & "{1}", _ e.TerminationException.GetType().FullName, _ e.TerminationException.Message)) ElseIf e.CompletionState = ActivityInstanceState.Canceled Then UpdateStatus("Workflow Canceled.") Else Dim Turns As Integer = Convert.ToInt32(e.Outputs("Turns")) UpdateStatus(String.Format("Congratulations, you guessed the number in {0} turns.", Turns)) End If GameOver() End SubwfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { if (e.CompletionState == ActivityInstanceState.Faulted) { UpdateStatus(string.Format("Workflow Terminated. Exception: {0}\r\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message)); } else if (e.CompletionState == ActivityInstanceState.Canceled) { UpdateStatus("Workflow Canceled."); } else { int Turns = Convert.ToInt32(e.Outputs["Turns"]); UpdateStatus(string.Format("Congratulations, you guessed the number in {0} turns.", Turns)); } GameOver(); }; -
添加以下
Aborted和OnUnhandledException处理程序。GameOver方法不从Aborted处理程序中调用,因为在工作流实例中止时,它并未终止,且以后可能恢复实例。wfApp.Aborted = _ Sub(e As WorkflowApplicationAbortedEventArgs) UpdateStatus(String.Format("Workflow Aborted. Exception: {0}" & vbCrLf & "{1}", _ e.Reason.GetType().FullName, _ e.Reason.Message)) End Sub wfApp.OnUnhandledException = _ Function(e As WorkflowApplicationUnhandledExceptionEventArgs) UpdateStatus(String.Format("Unhandled Exception: {0}" & vbCrLf & "{1}", _ e.UnhandledException.GetType().FullName, _ e.UnhandledException.Message)) GameOver() Return UnhandledExceptionAction.Terminate End FunctionwfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e) { UpdateStatus(string.Format("Workflow Aborted. Exception: {0}\r\n{1}", e.Reason.GetType().FullName, e.Reason.Message)); }; wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { UpdateStatus(string.Format("Unhandled Exception: {0}\r\n{1}", e.UnhandledException.GetType().FullName, e.UnhandledException.Message)); GameOver(); return UnhandledExceptionAction.Terminate; }; -
添加以下
PersistableIdle处理程序。 此处理程序检索添加的StringWriter扩展,提取WriteLine活动的输出,并将它显示在状态窗口中。wfApp.PersistableIdle = _ Function(e As WorkflowApplicationIdleEventArgs) 'Send the current WriteLine outputs to the status window. Dim writers = e.GetInstanceExtensions(Of StringWriter)() For Each writer In writers UpdateStatus(writer.ToString()) Next Return PersistableIdleAction.Unload End FunctionwfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e) { // Send the current WriteLine outputs to the status window. var writers = e.GetInstanceExtensions<StringWriter>(); foreach (var writer in writers) { UpdateStatus(writer.ToString()); } return PersistableIdleAction.Unload; };xref:System.Activities.PersistableIdleAction 枚举有三个值:xref:System.Activities.PersistableIdleAction.None、 xref:System.Activities.PersistableIdleAction.Persist 和 xref:System.Activities.PersistableIdleAction.Unload。 xref:System.Activities.PersistableIdleAction.Persist 会导致工作流持久保存,但不会导致工作流卸载。 xref:System.Activities.PersistableIdleAction.Unload 会导致工作流持久保存并卸载。
以下示例是完成的
ConfigureWorkflowApplication方法。Private Sub ConfigureWorkflowApplication(wfApp As WorkflowApplication) 'Configure the persistence store. wfApp.InstanceStore = store 'Add a StringWriter to the extensions. This captures the output 'from the WriteLine activities so we can display it in the form. Dim sw As New StringWriter() wfApp.Extensions.Add(sw) wfApp.Completed = _ Sub(e As WorkflowApplicationCompletedEventArgs) If e.CompletionState = ActivityInstanceState.Faulted Then UpdateStatus(String.Format("Workflow Terminated. Exception: {0}" & vbCrLf & "{1}", _ e.TerminationException.GetType().FullName, _ e.TerminationException.Message)) ElseIf e.CompletionState = ActivityInstanceState.Canceled Then UpdateStatus("Workflow Canceled.") Else Dim Turns As Integer = Convert.ToInt32(e.Outputs("Turns")) UpdateStatus(String.Format("Congratulations, you guessed the number in {0} turns.", Turns)) End If GameOver() End Sub wfApp.Aborted = _ Sub(e As WorkflowApplicationAbortedEventArgs) UpdateStatus(String.Format("Workflow Aborted. Exception: {0}" & vbCrLf & "{1}", _ e.Reason.GetType().FullName, _ e.Reason.Message)) End Sub wfApp.OnUnhandledException = _ Function(e As WorkflowApplicationUnhandledExceptionEventArgs) UpdateStatus(String.Format("Unhandled Exception: {0}" & vbCrLf & "{1}", _ e.UnhandledException.GetType().FullName, _ e.UnhandledException.Message)) GameOver() Return UnhandledExceptionAction.Terminate End Function wfApp.PersistableIdle = _ Function(e As WorkflowApplicationIdleEventArgs) 'Send the current WriteLine outputs to the status window. Dim writers = e.GetInstanceExtensions(Of StringWriter)() For Each writer In writers UpdateStatus(writer.ToString()) Next Return PersistableIdleAction.Unload End Function End Subprivate void ConfigureWorkflowApplication(WorkflowApplication wfApp) { // Configure the persistence store. wfApp.InstanceStore = store; // Add a StringWriter to the extensions. This captures the output // from the WriteLine activities so we can display it in the form. StringWriter sw = new StringWriter(); wfApp.Extensions.Add(sw); wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { if (e.CompletionState == ActivityInstanceState.Faulted) { UpdateStatus(string.Format("Workflow Terminated. Exception: {0}\r\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message)); } else if (e.CompletionState == ActivityInstanceState.Canceled) { UpdateStatus("Workflow Canceled."); } else { int Turns = Convert.ToInt32(e.Outputs["Turns"]); UpdateStatus(string.Format("Congratulations, you guessed the number in {0} turns.", Turns)); } GameOver(); }; wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e) { UpdateStatus(string.Format("Workflow Aborted. Exception: {0}\r\n{1}", e.Reason.GetType().FullName, e.Reason.Message)); }; wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { UpdateStatus(string.Format("Unhandled Exception: {0}\r\n{1}", e.UnhandledException.GetType().FullName, e.UnhandledException.Message)); GameOver(); return UnhandledExceptionAction.Terminate; }; wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e) { // Send the current WriteLine outputs to the status window. var writers = e.GetInstanceExtensions<StringWriter>(); foreach (var writer in writers) { UpdateStatus(writer.ToString()); } return PersistableIdleAction.Unload; }; }
若要启用启动和恢复多个工作流类型
要恢复工作流实例,主机必须提供工作流定义。 在此教程中有三个工作流类型,且后续教程步骤会介绍这些类型的多个版本。 主机应用程序可通过 WorkflowIdentity 将标识信息与持久化工作流实例相关联。 本节中的步骤演示了如何创建一个实用工具类,以帮助将工作流标识从持久化工作流实例映射到对应的工作流定义。 有关详细信息WorkflowIdentity和版本控制,请参阅使用 WorkflowIdentity 和版本控制。
-
右键单击NumberGuessWorkflowHost中解决方案资源管理器,然后选择添加,类。 类型
WorkflowVersionMap成名称框,然后单击添加。 -
在包含其他
using或Imports语句的文件的顶部添加以下using或Imports语句。Imports NumberGuessWorkflowActivities Imports System.Activitiesusing NumberGuessWorkflowActivities; using System.Activities; -
使用以下声明替换
WorkflowVersionMap类声明。Public Module WorkflowVersionMap Dim map As Dictionary(Of WorkflowIdentity, Activity) 'Current version identities. Public StateMachineNumberGuessIdentity As WorkflowIdentity Public FlowchartNumberGuessIdentity As WorkflowIdentity Public SequentialNumberGuessIdentity As WorkflowIdentity Sub New() map = New Dictionary(Of WorkflowIdentity, Activity) 'Add the current workflow version identities. StateMachineNumberGuessIdentity = New WorkflowIdentity With { .Name = "StateMachineNumberGuessWorkflow", .Version = New Version(1, 0, 0, 0) } FlowchartNumberGuessIdentity = New WorkflowIdentity With { .Name = "FlowchartNumberGuessWorkflow", .Version = New Version(1, 0, 0, 0) } SequentialNumberGuessIdentity = New WorkflowIdentity With { .Name = "SequentialNumberGuessWorkflow", .Version = New Version(1, 0, 0, 0) } map.Add(StateMachineNumberGuessIdentity, New StateMachineNumberGuessWorkflow()) map.Add(FlowchartNumberGuessIdentity, New FlowchartNumberGuessWorkflow()) map.Add(SequentialNumberGuessIdentity, New SequentialNumberGuessWorkflow()) End Sub Public Function GetWorkflowDefinition(identity As WorkflowIdentity) As Activity Return map(identity) End Function Public Function GetIdentityDescription(identity As WorkflowIdentity) As String Return identity.ToString() End Function End Modulepublic static class WorkflowVersionMap { static Dictionary<WorkflowIdentity, Activity> map; // Current version identities. static public WorkflowIdentity StateMachineNumberGuessIdentity; static public WorkflowIdentity FlowchartNumberGuessIdentity; static public WorkflowIdentity SequentialNumberGuessIdentity; static WorkflowVersionMap() { map = new Dictionary<WorkflowIdentity, Activity>(); // Add the current workflow version identities. StateMachineNumberGuessIdentity = new WorkflowIdentity { Name = "StateMachineNumberGuessWorkflow", Version = new Version(1, 0, 0, 0) }; FlowchartNumberGuessIdentity = new WorkflowIdentity { Name = "FlowchartNumberGuessWorkflow", Version = new Version(1, 0, 0, 0) }; SequentialNumberGuessIdentity = new WorkflowIdentity { Name = "SequentialNumberGuessWorkflow", Version = new Version(1, 0, 0, 0) }; map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow()); map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow()); map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow()); } public static Activity GetWorkflowDefinition(WorkflowIdentity identity) { return map[identity]; } public static string GetIdentityDescription(WorkflowIdentity identity) { return identity.ToString(); } }WorkflowVersionMap包含与此教程中的三个工作流定义对应的三个工作流标识,并在以下各节中工作流启动和恢复时使用。
若要启动新工作流
-
为
Click添加NewGame处理程序。 若要添加处理程序,请切换到设计视图的窗体,然后双击NewGame。 此时将添加NewGame_Click处理程序,视图将切换为窗体的代码视图。 每当用户单击此按钮时,就会启动新工作流。Private Sub NewGame_Click(sender As Object, e As EventArgs) Handles NewGame.Click End Subprivate void NewGame_Click(object sender, EventArgs e) { } -
将以下代码添加到 click 处理程序。 此代码创建工作流输入自变量的字典,以变量名称作为键。 此字典有一个条目,其中包含从范围组合框检索到的随机生成的数字范围。
Dim inputs As New Dictionary(Of String, Object)() inputs.Add("MaxNumber", Convert.ToInt32(NumberRange.SelectedItem))var inputs = new Dictionary<string, object>(); inputs.Add("MaxNumber", Convert.ToInt32(NumberRange.SelectedItem)); -
接下来,添加以下用于启动工作流的代码。 对应于所选工作流类型的
WorkflowIdentity和工作流定义通过WorkflowVersionMap帮助器类进行检索。 接下来,将使用工作流定义、WorkflowApplication和输入变量字典创建新的WorkflowIdentity实例。Dim identity As WorkflowIdentity = Nothing Select Case WorkflowType.SelectedItem.ToString() Case "SequentialNumberGuessWorkflow" identity = WorkflowVersionMap.SequentialNumberGuessIdentity Case "StateMachineNumberGuessWorkflow" identity = WorkflowVersionMap.StateMachineNumberGuessIdentity Case "FlowchartNumberGuessWorkflow" identity = WorkflowVersionMap.FlowchartNumberGuessIdentity End Select Dim wf As Activity = WorkflowVersionMap.GetWorkflowDefinition(identity) Dim wfApp = New WorkflowApplication(wf, inputs, identity)WorkflowIdentity identity = null; switch (WorkflowType.SelectedItem.ToString()) { case "SequentialNumberGuessWorkflow": identity = WorkflowVersionMap.SequentialNumberGuessIdentity; break; case "StateMachineNumberGuessWorkflow": identity = WorkflowVersionMap.StateMachineNumberGuessIdentity; break; case "FlowchartNumberGuessWorkflow": identity = WorkflowVersionMap.FlowchartNumberGuessIdentity; break; }; Activity wf = WorkflowVersionMap.GetWorkflowDefinition(identity); WorkflowApplication wfApp = new WorkflowApplication(wf, inputs, identity); -
接下来,添加以下代码,此代码将工作流添加到工作流列表中,并在窗体上显示工作流的版本信息。
'Add the workflow to the list and display the version information. WorkflowStarting = True InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id) WorkflowVersion.Text = identity.ToString() WorkflowStarting = False// Add the workflow to the list and display the version information. WorkflowStarting = true; InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id); WorkflowVersion.Text = identity.ToString(); WorkflowStarting = false; -
调用
ConfigureWorkflowApplication为此WorkflowApplication实例配置实例存储、扩展以及工作流生命周期处理程序。'Configure the instance store, extensions, and 'workflow lifecycle handlers. ConfigureWorkflowApplication(wfApp)// Configure the instance store, extensions, and // workflow lifecycle handlers. ConfigureWorkflowApplication(wfApp); -
最后,调用
Run。'Start the workflow. wfApp.Run()// Start the workflow. wfApp.Run();以下示例是完成的
NewGame_Click处理程序。Private Sub NewGame_Click(sender As Object, e As EventArgs) Handles NewGame.Click 'Start a new workflow. Dim inputs As New Dictionary(Of String, Object)() inputs.Add("MaxNumber", Convert.ToInt32(NumberRange.SelectedItem)) Dim identity As WorkflowIdentity = Nothing Select Case WorkflowType.SelectedItem.ToString() Case "SequentialNumberGuessWorkflow" identity = WorkflowVersionMap.SequentialNumberGuessIdentity Case "StateMachineNumberGuessWorkflow" identity = WorkflowVersionMap.StateMachineNumberGuessIdentity Case "FlowchartNumberGuessWorkflow" identity = WorkflowVersionMap.FlowchartNumberGuessIdentity End Select Dim wf As Activity = WorkflowVersionMap.GetWorkflowDefinition(identity) Dim wfApp = New WorkflowApplication(wf, inputs, identity) 'Add the workflow to the list and display the version information. WorkflowStarting = True InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id) WorkflowVersion.Text = identity.ToString() WorkflowStarting = False 'Configure the instance store, extensions, and 'workflow lifecycle handlers. ConfigureWorkflowApplication(wfApp) 'Start the workflow. wfApp.Run() End Subprivate void NewGame_Click(object sender, EventArgs e) { var inputs = new Dictionary<string, object>(); inputs.Add("MaxNumber", Convert.ToInt32(NumberRange.SelectedItem)); WorkflowIdentity identity = null; switch (WorkflowType.SelectedItem.ToString()) { case "SequentialNumberGuessWorkflow": identity = WorkflowVersionMap.SequentialNumberGuessIdentity; break; case "StateMachineNumberGuessWorkflow": identity = WorkflowVersionMap.StateMachineNumberGuessIdentity; break; case "FlowchartNumberGuessWorkflow": identity = WorkflowVersionMap.FlowchartNumberGuessIdentity; break; }; Activity wf = WorkflowVersionMap.GetWorkflowDefinition(identity); WorkflowApplication wfApp = new WorkflowApplication(wf, inputs, identity); // Add the workflow to the list and display the version information. WorkflowStarting = true; InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id); WorkflowVersion.Text = identity.ToString(); WorkflowStarting = false; // Configure the instance store, extensions, and // workflow lifecycle handlers. ConfigureWorkflowApplication(wfApp); // Start the workflow. wfApp.Run(); }
若要恢复的工作流
-
为
Click添加EnterGuess处理程序。 若要添加处理程序,请切换到设计视图的窗体,然后双击EnterGuess。 每当用户单击此按钮时,就会恢复工作流。Private Sub EnterGuess_Click(sender As Object, e As EventArgs) Handles EnterGuess.Click End Subprivate void EnterGuess_Click(object sender, EventArgs e) { } -
添加以下代码,以确保在工作流列表中选择了一个工作流,且用户的猜测有效。
If WorkflowInstanceId = Guid.Empty Then MessageBox.Show("Please select a workflow.") Return End If Dim userGuess As Integer If Not Int32.TryParse(Guess.Text, userGuess) Then MessageBox.Show("Please enter an integer.") Guess.SelectAll() Guess.Focus() Return End Ifif (WorkflowInstanceId == Guid.Empty) { MessageBox.Show("Please select a workflow."); return; } int guess; if (!Int32.TryParse(Guess.Text, out guess)) { MessageBox.Show("Please enter an integer."); Guess.SelectAll(); Guess.Focus(); return; } -
接下来,检索持久化工作流实例的
WorkflowApplicationInstance。WorkflowApplicationInstance表示尚未与工作流定义关联的持久化工作流实例。DefinitionIdentity的WorkflowApplicationInstance包含持久化工作流实例的WorkflowIdentity。 本教程中使用WorkflowVersionMap实用工具类,将WorkflowIdentity映射到正确的工作流定义。 检索工作流定义后,即使用正确的工作流定义创建WorkflowApplication。Dim instance As WorkflowApplicationInstance = _ WorkflowApplication.GetInstance(WorkflowInstanceId, store) 'Use the persisted WorkflowIdentity to retrieve the correct workflow 'definition from the dictionary. Dim wf As Activity = _ WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity) 'Associate the WorkflowApplication with the correct definition Dim wfApp As WorkflowApplication = _ New WorkflowApplication(wf, instance.DefinitionIdentity)WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store); // Use the persisted WorkflowIdentity to retrieve the correct workflow // definition from the dictionary. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity); // Associate the WorkflowApplication with the correct definition WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity); -
创建
WorkflowApplication后,请调用ConfigureWorkflowApplication以配置实例存储、工作流生命周期处理程序以及扩展。 每次创建新WorkflowApplication时都必须执行这些步骤,并且必须在将工作流实例加载到WorkflowApplication中之前完成。 在加载工作流后,此工作流通过用户的猜测恢复执行。'Configure the extensions and lifecycle handlers. 'Do this before the instance is loaded. Once the instance is 'loaded it is too late to add extensions. ConfigureWorkflowApplication(wfApp) 'Load the workflow. wfApp.Load(instance) 'Resume the workflow. wfApp.ResumeBookmark("EnterGuess", userGuess)// Configure the extensions and lifecycle handlers. // Do this before the instance is loaded. Once the instance is // loaded it is too late to add extensions. ConfigureWorkflowApplication(wfApp); // Load the workflow. wfApp.Load(instance); // Resume the workflow. wfApp.ResumeBookmark("EnterGuess", guess); -
最后,清除猜测文本框,并使窗体准备接受其他猜测。
'Clear the Guess textbox. Guess.Clear() Guess.Focus()// Clear the Guess textbox. Guess.Clear(); Guess.Focus();以下示例是完成的
EnterGuess_Click处理程序。Private Sub EnterGuess_Click(sender As Object, e As EventArgs) Handles EnterGuess.Click If WorkflowInstanceId = Guid.Empty Then MessageBox.Show("Please select a workflow.") Return End If Dim userGuess As Integer If Not Int32.TryParse(Guess.Text, userGuess) Then MessageBox.Show("Please enter an integer.") Guess.SelectAll() Guess.Focus() Return End If Dim instance As WorkflowApplicationInstance = _ WorkflowApplication.GetInstance(WorkflowInstanceId, store) 'Use the persisted WorkflowIdentity to retrieve the correct workflow 'definition from the dictionary. Dim wf As Activity = _ WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity) 'Associate the WorkflowApplication with the correct definition Dim wfApp As WorkflowApplication = _ New WorkflowApplication(wf, instance.DefinitionIdentity) 'Configure the extensions and lifecycle handlers. 'Do this before the instance is loaded. Once the instance is 'loaded it is too late to add extensions. ConfigureWorkflowApplication(wfApp) 'Load the workflow. wfApp.Load(instance) 'Resume the workflow. wfApp.ResumeBookmark("EnterGuess", userGuess) 'Clear the Guess textbox. Guess.Clear() Guess.Focus() End Subprivate void EnterGuess_Click(object sender, EventArgs e) { if (WorkflowInstanceId == Guid.Empty) { MessageBox.Show("Please select a workflow."); return; } int guess; if (!Int32.TryParse(Guess.Text, out guess)) { MessageBox.Show("Please enter an integer."); Guess.SelectAll(); Guess.Focus(); return; } WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store); // Use the persisted WorkflowIdentity to retrieve the correct workflow // definition from the dictionary. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity); // Associate the WorkflowApplication with the correct definition WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity); // Configure the extensions and lifecycle handlers. // Do this before the instance is loaded. Once the instance is // loaded it is too late to add extensions. ConfigureWorkflowApplication(wfApp); // Load the workflow. wfApp.Load(instance); // Resume the workflow. wfApp.ResumeBookmark("EnterGuess", guess); // Clear the Guess textbox. Guess.Clear(); Guess.Focus(); }
终止工作流
-
为
Click添加QuitGame处理程序。 若要添加处理程序,请切换到设计视图的窗体,然后双击QuitGame。 每当用户单击此按钮,即终止当前选择的工作流。Private Sub QuitGame_Click(sender As Object, e As EventArgs) Handles QuitGame.Click End Subprivate void QuitGame_Click(object sender, EventArgs e) { } -
将以下代码添加到
QuitGame_Click处理程序。 此代码首先进行检查,以确保在工作流列表中选择了一个工作流。 然后,它将该持久化实例加载到WorkflowApplicationInstance中,使用DefinitionIdentity确定正确的工作流定义,然后初始化WorkflowApplication。 接下来,通过调用ConfigureWorkflowApplication来配置扩展和工作流生命周期处理程序。WorkflowApplication配置好后,将加载它,然后调用Terminate。If WorkflowInstanceId = Guid.Empty Then MessageBox.Show("Please select a workflow.") Return End If Dim instance As WorkflowApplicationInstance = _ WorkflowApplication.GetInstance(WorkflowInstanceId, store) 'Use the persisted WorkflowIdentity to retrieve the correct workflow 'definition from the dictionary. Dim wf As Activity = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity) 'Associate the WorkflowApplication with the correct definition. Dim wfApp As WorkflowApplication = _ New WorkflowApplication(wf, instance.DefinitionIdentity) 'Configure the extensions and lifecycle handlers. ConfigureWorkflowApplication(wfApp) 'Load the workflow. wfApp.Load(instance) 'Terminate the workflow. wfApp.Terminate("User resigns.")if (WorkflowInstanceId == Guid.Empty) { MessageBox.Show("Please select a workflow."); return; } WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store); // Use the persisted WorkflowIdentity to retrieve the correct workflow // definition from the dictionary. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity); // Associate the WorkflowApplication with the correct definition WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity); // Configure the extensions and lifecycle handlers ConfigureWorkflowApplication(wfApp); // Load the workflow. wfApp.Load(instance); // Terminate the workflow. wfApp.Terminate("User resigns.");
生成并运行应用程序
-
双击Program.cs (或Module1.vb) 中解决方案资源管理器以显示其代码。
-
在包含其他
using(或Imports)语句的文件的顶部添加以下using(或Imports)语句。Imports System.Windows.Formsusing System.Windows.Forms; -
删除或注释掉现有的工作流承载代码从如何:运行工作流,并替换为以下代码。
Sub Main() Application.EnableVisualStyles() Application.Run(New WorkflowHostForm()) End Substatic void Main(string[] args) { Application.EnableVisualStyles(); Application.Run(new WorkflowHostForm()); } -
右键单击NumberGuessWorkflowHost中解决方案资源管理器,然后选择属性。 在中应用程序选项卡上,指定Windows 应用程序有关输出类型。 此步骤是可选的,但如果不执行此步骤,则除了窗体之外还会显示控制台窗口。
-
按 Ctrl+Shift+B 生成应用程序。
-
絋粄NumberGuessWorkflowHost是设置为启动应用程序,然后按 Ctrl + F5 启动应用程序。
-
选择一个范围的猜测和类型的工作流开始,然后单击新游戏。 输入在猜测猜测框,然后单击转提交该值。 请注意,
WriteLine活动的输出将显示在窗体上。 -
开始使用不同的工作流类型和数字范围的多个工作流,输入一些猜测值,并通过从选择的工作流之间进行切换工作流实例 Id列表。
请注意,当切换到新工作流时,状态窗口中不会显示以前的猜测值和工作流进度。 状态不可用的原因是未将它捕获并保存在任何位置。 本教程中,在下一步如何:创建自定义跟踪参与者,创建一个自定义跟踪参与者,它将保存此信息。
历史资料。此文对应 2019-08-18 的中文文档快照,适用产品版本和命令行为以原文为准。
来源与署名:Microsoft 和文档贡献者。固定版本原文。文档采用 CC BY 4.0,示例代码采用 MIT 授权。本站将 Markdown 转为 HTML,规范化链接,移除外部媒体、发布器占位标签和导航标记。
