.NET ValueTuple使用WhenAll获取多个任务结果

在.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(Task task0, Task 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(Task task0, Task task1, Task 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(Task task0, Task task1, Task task2, Task 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(Task task0, Task task1, Task task2, Task task3, Task 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(Task task0, Task task1, Task task2, Task task3, Task task4, Task 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(Task task0, Task task1, Task task2, Task task3, Task task4, Task task5, Task 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);

你可能感兴趣的:(.NET,C#)