Activity Automaton
The CLR virtualizes the instruction set of machine processors by describing its execution capabilities in terms of a hardware-agnostic instruction set, Microsoft Intermediate Language (MSIL). Programs compiled to MSIL are ultimately translated to machine-specific instructions, but virtualization allows language compilers to target only MSIL and not worry about various processor architectures.
In the WF programming model, the program statements used to build WF programs are classes that derive from Activity and CompositeActivity. Therefore, unlike MSIL, the "instruction set" supported by WF is not fixed. It is expected that many kinds of activities will be built and used in WF programs, while the WF runtime only relies upon the base classes. An activity developer can choose to implement anything—domain-specific or general-purpose—within the very general boundaries set by the WF runtime. Consequently, the WF runtime is freed from the actual semantics of specific activities.
The WF programming model does codify aspects of the interactions between the WF runtime and activities (such as the dispatch of execution handlers) in terms of an activity automaton (a finite state machine), which we will now explore in depth, with examples.
This chapter focuses solely on the normal execution of an activity. An activity that executes normally begins in the Initialized state, moves to the Executing state when its work begins, and moves to the Closed state when its work is completed. This is shown in Figure 3.2. The full activity automaton, shown in Figure 3.3, includes other states that will be discussed in Chapter 4, "Advanced Activity Execution."
Figure 3.2 Basic activity automaton
Figure 3.3 Complete activity automaton
The lifecycle of any activity in an executing WF program is captured by the states of the activity automaton and the transitions that exist between these states. Transitions from one state to another are brokered by the WF runtime to ensure the correctness of WF program execution.
Another way to view the activity automaton is as an abstract execution contract that exists between the WF runtime and any activity. It is the responsibility of the WF runtime to enforce that the execution of an activity strictly follows the transitions of the activity automaton. It is the responsibility of the activity to decide when certain transitions should occur. Figure 3.4 depicts the participation of both the WF scheduler and an activity in driving the automaton.
Figure 3.4 The dispatch of execution handlers is governed by the activity automaton.
Activity Execution Status and Result
The WriteLine activity shown in Listing 3.1 prints the value of its Text property to the console and then reports its completion.
Listing 3.1. WriteLine Activity
using System; using System.Workflow.ComponentModel; namespace EssentialWF.Activities { public class WriteLine : Activity { public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(WriteLine)); public string Text { get { return (string) GetValue(TextProperty); } set { SetValue(TextProperty, value); } } protected override ActivityExecutionStatus Execute( ActivityExecutionContext context) { Console.WriteLine(Text); return ActivityExecutionStatus.Closed; } } }
The execution logic of WriteLine is found in its override of the Execute method, which is inherited from Activity. The Execute method is the most important in a set of virtual methods defined on Activity that collectively constitute an activity's participation in the transitions of the activity automaton. All activities implement the Execute method; the other methods are more selectively overridden.
Listing 3.2 shows members defined by the Activity type that we will cover in this chapter and the next.
Listing 3.2. Activity Revisited
namespace System.Workflow.ComponentModel { public class Activity : DependencyObject { protected virtual ActivityExecutionStatus Cancel( ActivityExecutionContext context); protected virtual ActivityExecutionStatus Execute( ActivityExecutionContext context); protected virtual ActivityExecutionStatus HandleFault( ActivityExecutionContext context, Exception fault); protected virtual void Initialize( IServiceProvider provider); protected virtual void Uninitialize( IServiceProvider provider); protected virtual void OnExecutionContextLoad( IServiceProvider provider); protected virtual void OnExecutionContextUnload( IServiceProvider provider); protected virtual void OnClosed( IServiceProvider provider); public ActivityExecutionResult ExecutionResult { get; } public ActivityExecutionStatus ExecutionStatus { get; } /* *** other members *** */ } }
By returning a value of ActivityExecutionStatus.Closed from its Execute method, the WriteLine activity indicates to the WF runtime that its work is done; as a result, the activity moves to the Closed state.
Activity defines a property called ExecutionStatus, whose value indicates the current state (in the activity automaton) of the activity. The type of Activity.ExecutionStatus is ActivityExecutionStatus, which is shown in Listing 3.3.
Listing 3.3. ActivityExecutionStatus
namespace System.Workflow.ComponentModel { public enum ActivityExecutionStatus { Initialized, Executing, Canceling, Closed, Compensating, Faulting } }
Activity also defines a property called ExecutionResult, whose value qualifies an execution status of ExecutionStatus.Closed, because that state can be entered from any of five other states. The type of Activity.ExecutionResult is ActivityExecutionResult, which is shown in Listing 3.4. An activity with an execution status other than Closed will always have an execution result of None.
Listing 3.4. ActivityExecutionResult
namespace System.Workflow.ComponentModel { public enum ActivityExecutionResult { None, Succeeded, Canceled, Compensated, Faulted, Uninitialized, } }
The values of the ExecutionStatus and ExecutionResult properties are settable only by the WF runtime, which manages the lifecyle transitions of all activities.
You can determine the current execution status and execution result of an activity by getting the values of its ExecutionStatus and ExecutionResult properties:
using System; using System.Workflow.ComponentModel; public class MyActivity : Activity { protected override ActivityExecutionStatus Execute( ActivityExecutionContext context) { System.Diagnostics.Debug.Assert( ActivityExecutionStatus.Executing == ExecutionStatus); System.Diagnostics.Debug.Assert( ActivityExecutionResult.None == ExecutionResult); ... } }
The ExecutionStatus and ExecutionResult properties only have meaning at runtime for activities within a WF program instance.
Activity Execution Context
The Execute method has one parameter of type ActivityExecutionContext. This object represents the execution context for the currently executing activity.
The ActivityExecutionContext type (abbreviated AEC) is shown in Listing 3.5.
Listing 3.5. ActivityExecutionContext
namespace System.Workflow.ComponentModel { public sealed class ActivityExecutionContext: IDisposable, IServiceProvider { public T GetService<T>(); public object GetService(Type serviceType); public void CloseActivity(); /* *** other members *** */ } }
AEC has several roles in the WF programming model. The simplest view is that AEC makes certain WF runtime functionality available to executing activities. A comprehensive treatment of AEC will be given in Chapter 4.
The WF runtime manages ActivityExecutionContext objects carefully. AEC has only internal constructors, so only the WF runtime creates objects of this type. Moreover, AEC implements System.IDisposable. An AEC object is disposed immediately after the return of the method call (such as Activity.Execute) in which it is a parameter; if you try to cache an AEC object, you will encounter an ObjectDisposedException exception when you access its properties and methods. Allowing AEC objects to be cached could easily lead to violation of the activity automaton:
public class MyActivity : Activity { private ActivityExecutionContext cachedContext = null; protected override ActivityExecutionStatus Execute( ActivityExecutionContext context) { this.cachedContext = context; return ActivityExecutionStatus.Executing; } public void UseCachedContext() { // Next line will throw an ObjectDisposedException this.cachedContext.CloseActivity(); } }
Activity Services
ActivityExecutionContext has a role as a provider of services; these services are an activity's gateway to functionality that exists outside of the running WF program instance. AEC implements System.IServiceProvider and offers the required GetService method plus (for the sake of convenience) a typed GetService<T> wrapper over GetService. Using these methods, an activity can obtain services that are needed in order to complete its work.
In fact, AEC chains its service provider implementation to that of the WF runtime. This means that an activity can obtain custom services proffered by the application hosting the WF runtime, as shown in Figure 3.5.
Consider a WriterService that defines a Write method:
using System; namespace EssentialWF.Activities { public abstract class WriterService { public abstract void Write(string s); } }
By defining the writer service abstractly (we could also have used an interface), activities that use the service are shielded from details of how the service is implemented. We can change our implementation of the service over time without affecting activity code.
Here is a simple derivative of WriterService that uses the console to print the string that is provided to the Write method:
using System; using EssentialWF.Activities; namespace EssentialWF.Services { public class SimpleWriterService : WriterService { public override void Write(string s) { Console.WriteLine(s); } } }
Figure 3.5 Chaining of services
A SimpleWriterService object can be added to the WF runtime, which acts as a container of services:
using (WorkflowRuntime runtime = new WorkflowRuntime()) { runtime.AddService(new SimpleWriterService()); ... }
We can now change the execution logic of WriteLine to obtain a WriterService and call its Write method:
public class WriteLine : Activity { // Text property elided for clarity... protected override ActivityExecutionStatus Execute( ActivityExecutionContext context) { WriterService writer = context.GetService<WriterService>(); writer.Write(Text); return ActivityExecutionStatus.Closed; } }
This change may seem like a small matter, but if WriterService is defined as an abstract class (or an interface), it can have multiple implementations. In this way, the application hosting the WF runtime can choose the appropriate writer service without affecting WF program instances that contain WriteLine activities (that rely only upon the definition of that service).
In Chapter 6, "Transactions," we will bring transactions into the picture and explore how services used by activities (and activities themselves) can partipate in the transactions that attend the execution of WF program instances.