运行多个异步任务并等待它们全部完成 [英] Running multiple async tasks and waiting for them all to complete

查看:32
本文介绍了运行多个异步任务并等待它们全部完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在控制台应用程序中运行多个异步任务,并在进一步处理之前等待它们全部完成.

I need to run multiple async tasks in a console application, and wait for them all to complete before further processing.

那里有很多文章,但我似乎越读越困惑.我已经阅读并理解了 Task 库的基本原理,但我显然在某处遗漏了一个链接.

There's many articles out there, but I seem to get more confused the more I read. I've read and understand the basic principles of the Task library, but I'm clearly missing a link somewhere.

我知道可以链接任务,以便它们在另一个完成后开始(这几乎是我读过的所有文章的场景),但我希望我的所有任务同时运行,而且我想要全部完成后才能知道.

I understand that it's possible to chain tasks so that they start after another completes (which is pretty much the scenario for all the articles I've read), but I want all my Tasks running at the same time, and I want to know once they're all completed.

对于这样的场景,最简单的实现是什么?

What's the simplest implementation for a scenario like this?

推荐答案

两个答案都没有提到可等待的 Task.WhenAll:

Both answers didn't mention the awaitable Task.WhenAll:

var task1 = DoWorkAsync();
var task2 = DoMoreWorkAsync();

await Task.WhenAll(task1, task2);

Task.WaitAllTask.WhenAll 是前者会阻塞(类似于使用 Wait on单个任务),而后者不会也可以等待,将控制权交还给调用者,直到所有任务完成.

The main difference between Task.WaitAll and Task.WhenAll is that the former will block (similar to using Wait on a single task) while the latter will not and can be awaited, yielding control back to the caller until all tasks finish.

更重要的是,异常处理有所不同:

More so, exception handling differs:

Task.WaitAll:

至少一个 Task 实例被取消 - 或者 - 在至少一个 Task 实例的执行过程中抛出了异常.如果任务被取消,则 AggregateException 在其 InnerExceptions 集合中包含一个 OperationCanceledException.

At least one of the Task instances was canceled -or- an exception was thrown during the execution of at least one of the Task instances. If a task was canceled, the AggregateException contains an OperationCanceledException in its InnerExceptions collection.

Task.WhenAll:

如果任何提供的任务在故障状态下完成,返回的任务也将在故障状态下完成,其中的异常将包含来自每个提供的任务的未包装异常集的聚合.

If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

如果提供的任务没有一个出错,但至少有一个被取消,则返回的任务将以取消状态结束.

If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

如果没有任务发生故障并且没有任务被取消,则生成的任务将以 RanToCompletion 状态结束.如果提供的数组/枚举不包含任务,则返回的任务将在返回给调用者之前立即转换为 RanToCompletion 状态.

If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.

这篇关于运行多个异步任务并等待它们全部完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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