简体   繁体   English

C# AggregateException,在什么情况下我会聚合异常?

[英]C# AggregateException, in what scenario would I have aggregated exceptions?

I am probably missing a very obvious fact, but I have a hard time understanding the need for AggregatedExceptions.我可能错过了一个非常明显的事实,但我很难理解对 AggregatedExceptions 的需求。

I know since async/await we don't have to bother with AggregatedExceptions anymore (or at least are confronted with them less frequently).我知道自从 async/await 之后,我们就不必再为 AggregatedExceptions 烦恼了(或者至少不那么频繁地遇到它们了)。 I can relate to that, because I simply start a task and at some time I choose to synchronize the 'calling thread' with the 'task which runs in parallel'我可以与之相关,因为我只是启动一个任务,有时我选择将“调用线程”与“并行运行的任务”同步

var sometTask = DoSomethingInParallelAsync().ConfigureAwait(false);
...
...
await someTask;

In this scenario, an exception that occurred in DoSomethingInParallelAsync() will be presented to me when I await that call.在这种情况下, DoSomethingInParallelAsync()中发生的异常将在我等待该调用时呈现给我。

Why is that so different without using await , but Wait on the Task explicitly?为什么使用await的情况如此不同,而是明确地Wait Task

var someTask = DoSomethingInParallelAsync();
...
...
someTask.Wait();

An exception thrown in this example, will always wrap the thrown Exception in an AggregateException .此示例中抛出的异常将始终将抛出的Exception包装在AggregateException中。 I still don't understand why.我还是不明白为什么。

What can't I do when using async/await which takes away the need for AggregateException s?当使用 async/await 消除对AggregateException的需求时,我不能做什么?

Causing and handling the error错误的产生和处理

Task task1 = Task.Factory.StartNew(() => { throw new ArgumentException(); } );
Task task2 = Task.Factory.StartNew(() => { throw new UnauthorizedAccessException(); } );

try
{
    Task.WaitAll(task1, task2);
}
catch (AggregateException ae)
{
}

and also see that links并且还看到链接

here is an example: link2这是一个例子: link2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM