Search code examples
workflow-foundation-4

Parallel activities appear to execute sequentially


I am learning WF4 and got stuck at the following place. Please help.Thanks.

1) I have created a static method, MyMethod in a static class called Worker. Within this method I call Thread.Sleep(3000) and then print "MyMethod" called.
2) I then created an activity, DoWork (DoWork.xaml) which consists of a InvokeMethod (The target type is the Worker class in step 1 and MethodName = MyMethod).
3) In the main method, I call 2 methods called OutputSequence() and OutputParallel() which are as follows

private static void OutputSequence()            
{        
    Sequence s = new Sequence() { Activities = new DoWork(), new DoWork() } };    
    WorkflowInvoker.Invoke(s);    
}

private static void OutputParallel()            
{        
    Parallel p = new Parallel() { Branches = new DoWork(), new DoWork() } };    
    WorkflowInvoker.Invoke(p);    
}    

The OutputSequence() is OK as it calls the target method twice (in sequence) but the parallel one seems to execute sequentially as well. I expected it to execute in parallel.
What am I missing.


Solution

  • The Parallel activity is not what you think it is - it allows you to wait for things in parallel not to execute CPU based code in parallel. The WF4 threading mode is that there is exactly one thread at a time active in the workflow.

    If you put two delays in the parallel then both of those waits would occur in parallel as opposed to sequentially as they would in a sequence

    The idea is you want to wait for a number of actions when you don;t know the order in which they will occur. Then the parallel activity is complete when all of its child branches have completed