首页 > 代码库 > 《WF in 24 Hours》读书笔记 - Hour 3(1) - Workflow:添加宿主和事件监听
《WF in 24 Hours》读书笔记 - Hour 3(1) - Workflow:添加宿主和事件监听
1. 创建项目组,并添加一个Console Project和Activity Library,在Activity Library的项目中添加CodeActivity1和CodeActivity2,最终结构如下图所示:
2. CodeActivity1和2的代码如下:
1 public sealed class CodeActivity1 : CodeActivity 2 { 3 // Define an activity input argument of type string 4 public InArgument<string> Text { get; set; } 5 6 // If your activity returns a value, derive from CodeActivity<TResult> 7 // and return the value from the Execute method. 8 protected override void Execute(CodeActivityContext context) 9 { 10 Console.WriteLine("before delay: \‘{0}\‘", DateTime.Now.ToLongTimeString()); 11 } 12 } 13 14 public sealed class CodeActivity2 : CodeActivity 15 { 16 // Define an activity input argument of type string 17 public InArgument<string> Text { get; set; } 18 19 // If your activity returns a value, derive from CodeActivity<TResult> 20 // and return the value from the Execute method. 21 protected override void Execute(CodeActivityContext context) 22 { 23 Console.WriteLine("after delay: \‘{0}\‘", DateTime.Now.ToLongTimeString()); 24 } 25 }
3. 修改Activity1.xaml如下:
4. 修改Console Project的program.cs(注意,需要事先引入WorkflowsProject和System.Activities.dll)
1 static void Main(string[] args) 2 { 3 AutoResetEvent syncEvent = new AutoResetEvent(false); 4 5 Activity wf = new WorkflowsProject.Activity1(); 6 7 // Create the WorkflowApplication using the desired 8 // workflow definition. 9 WorkflowApplication wfApp = new WorkflowApplication(wf); 10 11 // Handle the desired lifecycle events. 12 wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) 13 { 14 Console.WriteLine("Workflow {0} completed.", e.InstanceId.ToString()); 15 syncEvent.Set(); 16 }; 17 18 wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e) 19 { 20 Console.WriteLine("Workflow {0} terminated because {1}", e.InstanceId, e.Reason.Message); 21 syncEvent.Set(); 22 }; 23 24 // Start the workflow. 25 wfApp.Run(); 26 27 // Wait for Completed to arrive and signal that 28 // the workflow is complete. 29 syncEvent.WaitOne(); 30 31 // Keep the console screen alive when workflow comnpletes 32 Console.WriteLine("Press enter to continue"); 33 Console.Read(); 34 }
5. 运行。结果如下:
总结:通过此例,我们可以看到通过WorkflowApplication,我们可以在宿主程序中启动Workflow,并且捕捉Workflow的事件。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。