在.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的自定义方法
代码语言:javascript复制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);
}
}
最后我们就可以通过下面代码片段去调用它了
代码语言:javascript复制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);