c# - 如何将两个任务结果合并为第三个任务?

标签 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<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;
}

这可行,但双 ContinueWith 似乎效率低下。有没有更好的方法来做到这一点,也许使用 TaskCompletionSource? (我不想使用锁或 Task.WaitAll。)

最佳答案

使用TaskFactory.ContinueWhenAll .

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

关于c# - 如何将两个任务结果合并为第三个任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10294302/

相关文章:

c# - 使用 Moq 在 C# 中单元测试 protected 方法

c# - DLLimport 返回 gobbledygook

c# - 在 Visual Studio 2010 中调试时出现 fatal error HRESULT=0x80131c08

具有接受参数的构造函数的 C# 单例

c# - 等待 ActionBlock<T> - TPL 数据流

c# - 获取所有者姓名

c# - 线程和SOLID原理

c# - 我如何在这种情况下使用任务?

c# - 为什么 Window.ShowDialog 没有阻塞在 TaskScheduler 任务中?

c# - 如何使用 TPL 在 C# 中编码(marshal)对特定线程的调用