并行活动似乎按顺序执行

时间:2012-01-22 19:30:12

标签: workflow-foundation-4

我正在学习WF4并被困在以下地方。请帮忙。谢谢。

1)我在名为Worker的静态类中创建了一个静态方法MyMethod。在这个方法中,我调用Thread.Sleep(3000),然后打印调用的“MyMethod” 2)然后我创建了一个活动,DoWork(DoWork.xaml),它包含一个InvokeMethod(目标类型是步骤1中的Worker类,MethodName = MyMethod)。
3)在main方法中,我调用了两个名为OutputSequence()和OutputParallel()的方法,如下所示

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);    
}    

OutputSequence()是正常的,因为它调用目标方法两次(按顺序),但并行方法似乎也顺序执行。我希望它能并行执行 我错过了什么

2 个答案:

答案 0 :(得分:7)

并行活动不是您认为的那样 - 它允许您并行等待并行执行基于CPU的代码。 WF4线程模式是工作流中一次只有一个线程。

如果在并行中放置两个延迟,那么这两个等待将并行发生,而不是顺序发生

这个想法是你想要等待一些行动,你不知道它们将发生的顺序。然后,当所有子分支完成时,并行活动完成

答案 1 :(得分:1)

实际上,并行活动实际上是逐个执行所有分支,并没有任何与并发代码执行相关的内容,就像两个线程一样。

但是有MS样本,显示并行活动内的块的“真正”并发执行。 .net 4中有AsyncCodeActivity,它允许并发执行活动。请检查http://msdn.microsoft.com/en-us/library/ee358731(VS.100).aspx 您可以在下面找到上面链接中的复制粘贴样本:

public sealed class GenerateRandom : AsyncCodeActivity<int>
{
    static Random r = new Random();

    protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
    {
        // Create a delegate that references the method that implements
        // the asynchronous work. Assign the delegate to the UserState,
        // invoke the delegate, and return the resulting IAsyncResult.
        Func<int> GetRandomDelegate = new Func<int>(GetRandom);
        context.UserState = GetRandomDelegate;
        return GetRandomDelegate.BeginInvoke(callback, state);
    }

    protected override int EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
    {
        // Get the delegate from the UserState and call EndInvoke
        Func<int> GetRandomDelegate = (Func<int>)context.UserState;
        return (int)GetRandomDelegate.EndInvoke(result);
    }

    int GetRandom()
    {
        // This activity simulates taking a few moments
        // to generate the random number. This code runs
        // asynchronously with respect to the workflow thread.
        Thread.Sleep(5000);

        return r.Next(1, 101);
    }
}

希望这对其他人有帮助

相关问题