Awaiting multiple Tasks with different results

后端 未结 10 1544
醉话见心
醉话见心 2020-11-22 12:59

I have 3 tasks:

private async Task FeedCat() {}
private async Task SellHouse() {}
private async Task BuyCar() {}
         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 13:28

    If you're using C# 7, you can use a handy wrapper method like this...

    public static class TaskEx
    {
        public static async Task<(T1, T2)> WhenAll(Task task1, Task task2)
        {
            return (await task1, await task2);
        }
    }
    

    ...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.

    var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());
    

    However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.

提交回复
热议问题