在.NET中,我們可以通過Task.WhenAll用來等待多個任務。任務完成之後,我們可以使用await等待他們來獲取結果。 Task<int> task1 = Task.Run(() => 1); Task<string> task2 = Task.Run(() => "hello"); awai ...
在.NET中,我們可以通過Task.WhenAll
用來等待多個任務。任務完成之後,我們可以使用await
等待他們來獲取結果。
Task<int> task1 = Task.Run(() => 1);
Task<string> task2 = Task.Run(() => "hello");
await Task.WhenAll(task1, task2);
var task1Result = task1.Result; // or await task1
var task2Result = task2.Result; // or await task2
我們再來看一下如何用WhenAll
方法來獲取結果。
Task<int> task1 = Task.Run(() => 1);
Task<string> task2 = Task.Run(() => "hello");
var (task1Result, task2Result) = await Task.WhenAll(task1, task2);
當然我們可以編寫一個帶有任務結果的ValueTuple的自定義方法
public static class TaskEx
{
public static async Task<(T0, T1)> WhenAll<T0, T1>(Task<T0> task0, Task<T1> task1)
{
await Task.WhenAll(task0, task1).ConfigureAwait(false);
// It's ok to use task.Result here as the task is completed
return (task0.Result, task1.Result);
}
public static async Task<(T0, T1, T2)> WhenAll<T0, T1, T2>(Task<T0> task0, Task<T1> task1, Task<T2> task2)
{
await Task.WhenAll(task0, task1, task2).ConfigureAwait(false);
return (task0.Result, task1.Result, task2.Result);
}
public static async Task<(T0, T1, T2, T3)> WhenAll<T0, T1, T2, T3>(Task<T0> task0, Task<T1> task1, Task<T2> task2, Task<T3> task3)
{
await Task.WhenAll(task0, task1, task2, task3).ConfigureAwait(false);
return (task0.Result, task1.Result, task2.Result, task3.Result);
}
public static async Task<(T0, T1, T2, T3, T4)> WhenAll<T0, T1, T2, T3, T4>(Task<T0> task0, Task<T1> task1, Task<T2> task2, Task<T3> task3, Task<T4> task4)
{
await Task.WhenAll(task0, task1, task2, task3, task4).ConfigureAwait(false);
return (task0.Result, task1.Result, task2.Result, task3.Result, task4.Result);
}
public static async Task<(T0, T1, T2, T3, T4, T5)> WhenAll<T0, T1, T2, T3, T4, T5>(Task<T0> task0, Task<T1> task1, Task<T2> task2, Task<T3> task3, Task<T4> task4, Task<T5> task5)
{
await Task.WhenAll(task0, task1, task2, task3, task4, task5).ConfigureAwait(false);
return (task0.Result, task1.Result, task2.Result, task3.Result, task4.Result, task5.Result);
}
public static async Task<(T0, T1, T2, T3, T4, T5, T6)> WhenAll<T0, T1, T2, T3, T4, T5, T6>(Task<T0> task0, Task<T1> task1, Task<T2> task2, Task<T3> task3, Task<T4> task4, Task<T5> task5, Task<T6> task6)
{
await Task.WhenAll(task0, task1, task2, task3, task4, task5, task6).ConfigureAwait(false);
return (task0.Result, task1.Result, task2.Result, task3.Result, task4.Result, task5.Result, task6.Result);
}
}
最後我們就可以通過下麵代碼片段去調用它了
Task<int> task1 = Task.Run(() => 1);
Task<string> task2 = Task.Run(() => "hello");
Task<string> task2 = Task.Run(() => 'fh');
var (t1Result, t2Result, t3Result) = await TaskEx.WhenAll(task1, task2, task3);