Windows Workflow Parallel Activity – How to get things to actually run in parallel

I’ve been doing something using Windows Workflow, and it is….interesting.  Someday we will have a great way to code workflows, in the meantime, there are things like Windows Workflow.

Anyhoo, one thing that took a while to figure out is how to get a parallel activity to actually run things in, well, parallel.  By default, it actually doesn’t.  There is one thread assigned to the entire activity, and so, if any of your child activities do their work synchronously, they will not yield to any of the other child activities until they are complete.  This is, well, a little annoying.

However, it is fairly easy to get it to work properly, and the solution is to use Tasks.

So, inside your BeginExecute method, you will want to use Task.Factory.StartNew. 

Here’s some boilerplate sample code:

protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
// setup variables here.  note, you cannot reference 'context' inside of the task, so you need to get whatever values you need ahead of time

    List<int> inputvalues = context.GetValue(MyInts);

    Task<List<string>> worker = Task.Factory.StartNew(o =>
        // imagine this runs for a while
        List<string> returnValues = new MyProcessThatProducesTheReturnValue(inputvalues);
        return returnValues;
    }, state);

    worker.ContinueWith(task => callback(task));
    return worker;

And then:

protected override List<string> EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
    var worker = result as Task<List<string>>;
    if (worker == null) throw new ArgumentException("result is null");
    return worker.Result;

This allows your activity to run on a separate thread in parallel.

posted on Tuesday, January 06, 2015 10:08 AM Print
No comments posted yet.

Post Comment

Title *
Name *
Comment *  
Please add 4 and 8 and type the answer here: