WaitAll vs WhenAll

本文翻译自:WaitAll vs WhenAll

What is the difference between Task.WaitAll() and Task.WhenAll() from the Async CTP ? Task.WaitAll()和Async CTP的Task.WhenAll()什么区别? Can you provide some sample code to illustrate the different use cases ? 您能提供一些示例代码来说明不同的用例吗?


#1楼

参考:https://stackoom.com/question/Pgyc/WaitAll-vs-WhenAll


#2楼

As an example of the difference -- if you have a task the does something with the UI thread (eg a task that represents an animation in a Storyboard) if you Task.WaitAll() then the UI thread is blocked and the UI is never updated. 作为差异的一个例子 - 如果你有一个任务,用UI线程做一些事情(例如,一个表示故事板中动画的任务),如果你是Task.WaitAll()那么UI线程被阻止,UI永远不会更新。 if you use await Task.WhenAll() then the UI thread is not blocked, and the UI will be updated. 如果您使用await Task.WhenAll()则不会阻止UI线程,并且将更新UI。


#3楼

While JonSkeet's answer explains the difference in a typically excellent way for me the biggest practical difference is exception handling . 虽然JonSkeet的回答以一种典型的优秀方式解释了差异,但最大的实际区别是异常处理 EDIT: Agreed - it's not the biggest practical difference, it's a difference. 编辑:同意 - 这不是最大的实际差异,这是一个区别。

Task.WaitAll throws an AggregateException when any of the tasks throws and you can examine all thrown exceptions. 当任何任务抛出时, Task.WaitAll抛出一个AggregateException ,您可以检查所有抛出的异常。 The await in await Task.WhenAll unwraps the AggregateException and 'returns' only the first exception. awaitawait Task.WhenAll解开了AggregateException和“返回”只有第一个例外。

When the program below executes with await Task.WhenAll(taskArray) the output is as follows. 当下面的程序执行await Task.WhenAll(taskArray) ,输出如下。

19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.

When the program below is executed with Task.WaitAll(taskArray) the output is as follows. 当使用Task.WaitAll(taskArray)执行以下程序时,输出如下。

19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.

The program: 该程序:

class MyAmazingProgram
{
    public class CustomException : Exception
    {
        public CustomException(String message) : base(message)
        { }
    }

    static void WaitAndThrow(int id, int waitInMs)
    {
        Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");

        Thread.Sleep(waitInMs);
        throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
    }

    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await MyAmazingMethodAsync();
        }).Wait();

    }

    static async Task MyAmazingMethodAsync()
    {
        try
        {
            Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
                                 Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };

            Task.WaitAll(taskArray);
            //await Task.WhenAll(taskArray);
            Console.WriteLine("This isn't going to happen");
        }
        catch (AggregateException ex)
        {
            foreach (var inner in ex.InnerExceptions)
            {
                Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
        }
        Console.WriteLine("Done.");
        Console.ReadLine();
    }
}

#4楼

What do they do: 他们在做什么:

  • Internally both do the same thing. 在内部都做同样的事情。

What's the difference: 有什么不同:

  • WaitAll is a blocking call WaitAll是一个阻止呼叫
  • WhenAll - not - code will continue executing WhenAll - not - 代码将继续执行

Use which when: 使用时:

  • WaitAll when cannot continue without having the result WaitAll什么时候无法继续而没有结果
  • WhenAll when what just to be notified, not blocked WhenAll时只是通知一下,不堵塞

#5楼

Task.WaitAll blocks the current thread until everything has completed. Task.WaitAll阻止当前线程,直到一切都完成。

Task.WhenAll returns a task which represents the action of waiting until everything has completed. Task.WhenAll返回一个任务 ,表示等待一切都完成的动作。

That means that from an async method, you can use: 这意味着从异步方法,您可以使用:

await Task.WhenAll(tasks);

... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time. ...这意味着你的方法将在一切都完成后继续,但是你不会把一个线程绑在那里直到那个时候。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值