1. 创建项目组,并添加一个Console Project和Activity Library,在Activity Library的项目中添加CodeActivity1和CodeActivity2,最终结构如下图所示:
2. CodeActivity1和2的代码如下:
public sealed class CodeActivity1 : CodeActivity
{
// Define an activity input argument of type string
public InArgument<string> Text { get; set; } // If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
Console.WriteLine("before delay: \'{0}\'", DateTime.Now.ToLongTimeString());
}
} public sealed class CodeActivity2 : CodeActivity
{
// Define an activity input argument of type string
public InArgument<string> Text { get; set; } // If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
Console.WriteLine("after delay: \'{0}\'", DateTime.Now.ToLongTimeString());
}
}
3. 修改Activity1.xaml如下:
4. 修改Console Project的program.cs(注意,需要事先引入WorkflowsProject和System.Activities.dll)
static void Main(string[] args)
{
AutoResetEvent syncEvent = new AutoResetEvent(false); Activity wf = new WorkflowsProject.Activity1(); // Create the WorkflowApplication using the desired
// workflow definition.
WorkflowApplication wfApp = new WorkflowApplication(wf); // Handle the desired lifecycle events.
wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{
Console.WriteLine("Workflow {0} completed.", e.InstanceId.ToString());
syncEvent.Set();
}; wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
{
Console.WriteLine("Workflow {0} terminated because {1}", e.InstanceId, e.Reason.Message);
syncEvent.Set();
}; // Start the workflow.
wfApp.Run(); // Wait for Completed to arrive and signal that
// the workflow is complete.
syncEvent.WaitOne(); // Keep the console screen alive when workflow comnpletes
Console.WriteLine("Press enter to continue");
Console.Read();
}
5. 运行。结果如下:
总结:通过此例,我们可以看到通过WorkflowApplication,我们可以在宿主程序中启动Workflow,并且捕捉Workflow的事件。