WF4 Asynchronous Workflows

If you are like me, you may have been surprised when you read the MSDN documentation for System.Activities.Statements.Parallel.

A Parallel activity operates by simultaneously scheduling each Activity in its Branches collection at the start. It completes when all of its Branches complete or when its CompletionCondition property evaluates to true. While all the Activity objects run asynchronously, they do not execute on separate threads, so each successive activity only executes when the previously scheduled activity completes or goes idle. If none of the child activities of this activity go idle, this activity execute in the same way that a **Sequence** activity does.

-MSDN (http://msdn.microsoft.com/en-us/library/system.activities.statements.parallel.aspx)

While the name implies that each branch of activities would be executed on a separate thread, the Parallel activity does not execute activities on separate threads.  In fact, all activities in a workflow execute on the same thread.  This is very similar to how in Windows Forms and WPF, all code that manipulates the user interface must be executed on the UI thread.  You might be asking yourself:  What is the point of this parallel activity?

It is possible for some activity to execute work on a background thread.  When combined with the Parallel activity (or the ParallelForEach activity), this allows the workflow runtime to schedule other activities to be executed while it is waiting for the background thread to complete.  WF4 comes with a number of asynchronous activities that can be used in this way.  Some examples are the Delay, InvokeMethod (when RunAsynchronously is set to true).  If you are creating custom activities, you can also create activities that execute asynchronously.  If you are implementing a code-based activity, you can inherit from AsyncCodeActivity.  If you are implementing more complex activities that need to make use of the workflow runtime, there are a couple strategies for implementing asynchronous activities.  One option is to use the parallel extensions introduced in .NET 4 (Workflow and Parallel Extensions).   Another option is to use bookmarks.

However, if you want to compose a workflow in XAML and have that workflow executed in parallel, your options are more limited.  Here’s an example:

In this example, I would like the 2 workflows to execute on a separate thread.  The output, however, shows that both activities are executed on the same thread:

Luckily, there is a way to accomplish this using a dynamic activity to execute a child activity on a background thread.  The child activity can be any activity (including Sequence or FlowChart), so this allows us to execute any portion of a workflow on a background thread. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Threading.Tasks;
using System.ComponentModel;
using Microsoft.VisualBasic.Activities;

namespace ParallelActivities
{
[Designer(typeof(AsyncActivityWrapperDesigner))]
public class AsyncActivityWrapper : AsyncCodeActivity
{
public AsyncActivityWrapper()
{
Body = new ActivityAction();
}

    [Browsable(false)]
    public ActivityAction Body { get; set; }

    protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
    {        
         Activity activity = CreateDynamicActivity(context);
        IDictionary inputs = GetArgumentsAndVariables(context);
        Task task = Task.Factory.StartNew((ignore) =>
        {
            WorkflowInvoker.Invoke(activity, inputs);

        }, state);
        task.ContinueWith((t) => callback(t));
        return task;
    }

    protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
    {            
    }

    private Activity CreateDynamicActivity(AsyncCodeActivityContext context)
    {
        DynamicActivity result = new DynamicActivity();
        //Create a DynamicActivityProperty for each argument / variable in the current context
        foreach (PropertyDescriptor property in context.DataContext.GetProperties())
        {
            DynamicActivityProperty dynamicActivityProperty = new DynamicActivityProperty();

            dynamicActivityProperty.Name = property.Name;
            dynamicActivityProperty.Type = typeof(InArgument<>).MakeGenericType(property.PropertyType);
            dynamicActivityProperty.Value = Activator.CreateInstance(dynamicActivityProperty.Type);
            result.Properties.Add(dynamicActivityProperty);
        }

        //Copy impors to dynamic activity;
        VisualBasic.SetSettings(result, VisualBasic.GetSettings(this));
        result.Implementation = () => Body.Handler;
        return result;
    }

    private IDictionary GetArgumentsAndVariables(AsyncCodeActivityContext context)
    {
        IDictionary result = new Dictionary();

        foreach (PropertyDescriptor property in context.DataContext.GetProperties())
        {
            result.Add(property.Name, property.GetValue(context.DataContext));
        }

        return result;
    }
}

}

Using the AsyncActivityWrapper inside a Parallel activity accomplishes the desired behavior by executing activities inside the AsyncActivityWrapper as shown here:

With the AsyncActivityWrapper, we can see that each branch of the Parallel activity is executed on a separate thread:

The designer for this activity is actually very simple.  It contains a single WorkfowItemPresenter which allows us to drag and drop an activity into the AsyncActivityWrapper.


<sap:ActivityDesigner x:Class="ParallelActivities.AsyncActivityWrapperDesigner"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
    xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation">

    <sap:WorkflowItemPresenter Margin="7" Item="{Binding Path=ModelItem.Body.Handler, Mode=TwoWay}" HintText="Drop Activity"/>

</sap:ActivityDesigner>

In conclusion, the AsyncActivityWrapper can be used to execute portions of a workflow on a separate thread.  When combined with the Parallel or ParallelForEach activities, this allows us to execute multiple activities in parallel.  In situations where a workflow is processing a large amount of data, or doing a large number of complex calculations, the AsyncActivityWrapper can help to improve performance.  The implementation provided here does have some limitations.  As with any parallel programming, you need to make sure that activities that are executing in parallel do not conflict with each other.  If the activities are trying to access and manipulate the same data, you might run into problems.  If the activities have a return value, you may need an alternate implementation of AsyncActivityWrapper that inherits from AsyncCodeActivity<TResult>.  Also, since each activity is being executed as a separate independant workflow, you will lose some workflow functionality such as Persistence and Tracking.