雙擊設計器圖標進入 Workflow1.cs 撰寫 ExecuteCode 事件:
namespace CodeAndDelay {
public sealed partial class Workflow1 : SequentialWorkflowActivity {
public Workflow1() { InitializeComponent(); }
private void codeActivity1_ExecuteCode(object sender, EventArgs e) {
Console.WriteLine("\n這裡是活動一的執行代碼,當前時間為{0}。", DateTime.Now);
}
private void codeActivity2_ExecuteCode(object sender, EventArgs e) {
Console.WriteLine("\n這裡是活動二的執行代碼,當前時間為{0}。", DateTime.Now);
}
}
}
選取延遲活動圖標,屬性視窗設定 TimeoutDuration = 00:00:05 (時:分:秒格式)。
using System;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Threading;
namespace CodeAndDelay {
class Program {
static void Main(string[] args) {
using (WorkflowRuntime workflowRuntime = new WorkflowRuntime()) {
AutoResetEvent waitHandle = new AutoResetEvent(false);
workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { waitHandle.Set(); };
workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) {
Console.WriteLine(e.Exception.Message);
waitHandle.Set();
};
WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(CodeAndDelay.Workflow1));
instance.Start();
waitHandle.WaitOne(); // 等待工作流完成
}
}
}
}
注意:工作流以非同步獨立執行緒執行,AutoResetEvent 同步等待完成。詳細討論留待後續文章。