Terminating a WF Program Instance


A WF program instance can be terminated by calling the Terminate method of the WorkflowInstance class. A WF program instance will also be terminated if an exception in the program propagates to the root activity and is not handled, or if a TerminateActivity within the WF program is executed. The TerminateActivity class is defined in the System.Workflow.ComponentModel namespace and is shown in Listing 5.17.

Listing 5.17. TerminateActivity

 namespace System.Workflow.ComponentModel {   public sealed class TerminateActivity : Activity   {     public string Error { get; set; }     /* *** other members *** */   } } 


Use of TerminateActivity in XAML looks like this:

 <wf:TerminateActivity x:Name="t1" Error="Cannot proceed" /> 


The WorkflowRuntime has a WorkflowTerminated event, which is raised whenever a WF program instance is terminated. Termination of a WF program instance is considered abnormal completion. Thus, the WorkflowTerminatedEventArgs that carries the data for the WorkflowTerminated event contains one property of type Exception. This exception is either an unhandled exception that occurred within the instance or, if the Terminate method of WorkflowInstance was called by the host application (or a TerminateActivity within the WF program executed) a special WorkflowTerminatedException, which carries the error string that was reported as part of the termination.

Listing 5.18 shows the WorkflowTerminatedEventArgs type.

Listing 5.18. WorkflowTerminatedEventArgs

 namespace System.Workflow.Runtime {   public class WorkflowTerminatedEventArgs : WorkflowEventArgs   {     public Exception Exception { get; }   } } 


Calling WorkflowInstance.Terminate causes the execution of the program instance to end immediately. As part of termination, the WF program instance is persisted and removed from memory. Although a WF program instance is persisted as part of termination, its execution can never be continued. The instance has irrevocably transitioned to the Terminated state. Instance termination is illustrated in Listing 5.19.

Listing 5.19. WF Program Instance Termination

 static void Main() {     using(WorkflowRuntime runtime = new WorkflowRuntime())   {     runtime.StartRuntime();     runtime.WorkflowTerminated += delegate(       object sender, WorkflowTerminatedEventArgs e)     {       Console.WriteLine("Instance terminated: " +         e.WorkflowInstance.InstanceId);       Console.WriteLine("Exception message: " +         e.Exception.Message);     };     WorkflowInstance instance = ...     instance.Terminate("Need to terminate it");     ...   } } 





Essential Windows Workflow Foundation
Essential Windows Workflow Foundation
ISBN: 0321399838
EAN: 2147483647
Year: 2006
Pages: 97

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net