2012-04-24 58 views
7

如何執行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。)

回答

17

使用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)); 
    } 
+0

這看起來像我想要的,雖然你連接的「ContinueWhenAll」超載不會返回或者返回任務。如果您更新鏈接到http://msdn.microsoft.com/en-us/library/ee362175.aspx,我會接受您的答案。 – 2012-04-24 08:45:44

+0

美麗!我錯過了ContinueWhenAll。乾杯! – 2012-04-24 08:52:30

相關問題