C# 如何将两个任务结果合并到第三个任务中?

C# 如何将两个任务结果合并到第三个任务中?,c#,task-parallel-library,C#,Task Parallel Library,如何执行System.Threading.Task作为两个或多个其他任务结果的延续 public Task<FinalResult> RunStepsAsync() { Task<Step1Result> task1 = Task<Step1Result>.Factory.StartNew(Step1); // Use the result of step 1 in steps 2A and 2B Task<Step2AResu

如何执行System.Threading.Task作为两个或多个其他任务结果的延续

public Task<FinalResult> RunStepsAsync()
{
    Task<Step1Result> task1 = Task<Step1Result>.Factory.StartNew(Step1);

    // Use the result of step 1 in steps 2A and 2B
    Task<Step2AResult> task2A = task1.ContinueWith(t1 => Step2A(t1.Result));
    Task<Step2BResult> task2B = task1.ContinueWith(t1 => Step2B(t1.Result));

    // Now merge the results of steps 2A and 2B in step 3
    Task<FinalResult> task3 = task2A
        .ContinueWith(
            t2A => task2B.ContinueWith(
                t2B => Step3(t2A.Result, t2B.Result)))
        .Unwrap();
    return task3;
}
公共任务RunStepsAsync()
{
Task task1=Task.Factory.StartNew(步骤1);
//在步骤2A和2B中使用步骤1的结果
任务task2A=task1.继续(t1=>Step2A(t1.Result));
task2B=task1.继续(t1=>Step2B(t1.Result));
//现在将步骤2A和2B的结果合并到步骤3中
任务task3=task2A
.继续(
t2A=>task2B.ContinueWith(
t2B=>Step3(t2A.Result,t2B.Result)))
.Unwrap();
返回任务3;
}
这是可行的,但双连续体似乎效率低下。有没有更好的方法来做到这一点,也许是使用TaskCompletionSource?(我不想使用锁或Task.WaitAll。)

使用

class Step1Result{}
类Step2AResult
{
公共Step2AResult(Step1Result结果){}
}
类Step2BResult
{
公共Step2BResult(Step1Result结果){}
}
课程最终结果
{
公共财务结果(Step2AResult Step2AResult,Step2BResult Step2BResult){}
}
公共任务RunStepsAsync()
{
var task1=Task.Factory.StartNew(()=>newstep1result());
//在步骤2A和2B中使用步骤1的结果
var task2A=task1.ContinueWith(t1=>newstep2aResult(t1.Result));
var task2B=task1.ContinueWith(t1=>newstep2bresult(t1.Result));
//现在将步骤2A和2B的结果合并到步骤3中
返回任务
.工厂
.ContinueWhenAll(新任务[]{task2A,task2B},tasks=>newfinalresult(task2A.Result,task2B.Result));
}

这看起来像是我想要的,尽管您链接到的
continuewheall
重载不会接受或返回
任务
。如果你更新你的链接到,我会接受你的答案。漂亮!我错过了一切。干杯
class Step1Result {}
class Step2AResult
{
    public Step2AResult(Step1Result result) {}
}
class Step2BResult
{
    public Step2BResult(Step1Result result) {}
}
class FinalResult 
{
    public FinalResult(Step2AResult step2AResult, Step2BResult step2BResult) {}
}

    public Task<FinalResult> RunStepsAsync()
    {
        var task1 = Task<Step1Result>.Factory.StartNew(() => new Step1Result());

        // Use the result of step 1 in steps 2A and 2B
        var task2A = task1.ContinueWith(t1 => new Step2AResult(t1.Result));
        var task2B = task1.ContinueWith(t1 => new Step2BResult(t1.Result));

        // Now merge the results of steps 2A and 2B in step 3
        return Task <FinalResult>
            .Factory
            .ContinueWhenAll(new Task[] { task2A, task2B }, tasks => new FinalResult(task2A.Result, task2B.Result));
    }