为什么我应该更喜欢单个“await Task.WhenAll"而不是多个等待? [英] Why should I prefer single 'await Task.WhenAll' over multiple awaits?

查看:35
本文介绍了为什么我应该更喜欢单个“await Task.WhenAll"而不是多个等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不关心任务完成的顺序,只需要它们全部完成,我还应该使用 await Task.WhenAll 而不是多个 await 吗?例如,DoWork2 是否低于 DoWork1 的首选方法(为什么?):

In case I do not care about the order of task completion and just need them all to complete, should I still use await Task.WhenAll instead of multiple await? e.g, is DoWork2 below a preferred method to DoWork1 (and why?):

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static async Task<string> DoTaskAsync(string name, int timeout)
        {
            var start = DateTime.Now;
            Console.WriteLine("Enter {0}, {1}", name, timeout);
            await Task.Delay(timeout);
            Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds);
            return name;
        }

        static async Task DoWork1()
        {
            var t1 = DoTaskAsync("t1.1", 3000);
            var t2 = DoTaskAsync("t1.2", 2000);
            var t3 = DoTaskAsync("t1.3", 1000);

            await t1; await t2; await t3;

            Console.WriteLine("DoWork1 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
        }

        static async Task DoWork2()
        {
            var t1 = DoTaskAsync("t2.1", 3000);
            var t2 = DoTaskAsync("t2.2", 2000);
            var t3 = DoTaskAsync("t2.3", 1000);

            await Task.WhenAll(t1, t2, t3);

            Console.WriteLine("DoWork2 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
        }


        static void Main(string[] args)
        {
            Task.WhenAll(DoWork1(), DoWork2()).Wait();
        }
    }
}

推荐答案

是的,使用 WhenAll 因为它一次传播所有错误.使用多个等待,如果较早的等待之一抛出,您将丢失错误.

Yes, use WhenAll because it propagates all errors at once. With the multiple awaits, you lose errors if one of the earlier awaits throws.

另一个重要的区别是 WhenAll 将等待所有任务完成即使存在失败(错误或取消的任务).手动按顺序等待会导致意外并发,因为您的程序中想要等待的部分实际上会提前继续.

Another important difference is that WhenAll will wait for all tasks to complete even in the presence of failures (faulted or canceled tasks). Awaiting manually in sequence would cause unexpected concurrency because the part of your program that wants to wait will actually continue early.

我认为这也使阅读代码更容易,因为您想要的语义直接记录在代码中.

I think it also makes reading the code easier because the semantics that you want are directly documented in code.

这篇关于为什么我应该更喜欢单个“await Task.WhenAll"而不是多个等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆