Task.WhenAny和不可观测异常 [英] Task.WhenAny and Unobserved Exceptions

查看:953
本文介绍了Task.WhenAny和不可观测异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有三个任务, A B C 。所有三个都保证在1和5秒之间的随机时间抛出异常。然后我写了下面的code:

 等待Task.WhenAny(A,B,C);
 

这最终将首先抛出从哪个任务故障异常。由于没有的try ... catch 在这里,这个异常会冒泡到其他地方在我的code。

在剩下的两个任务抛出一个异常,会发生什么?不是这些未观察到的异常,这将导致整个过程被杀害?这是否意味着,用唯一的办法 WhenAny 是一个的try ... catch 块,然后以某种方式里面继续之前观察剩下的两个任务是什么?

追问:我想,答案既适用于.NET 4.5的的.NET 4.0的异步定位包(虽然明确使用 TaskEx.WhenAny 在这种情况下)。

解决方案
  

在剩下的两个任务抛出一个异常,会发生什么?

这些工作旨意完成故障状态。

  

难道这些未观察到的异常,这将导致整个过程被杀害?

现在不一样了。

在.NET 4.0中,工作的析构函数将通过其未观测到的异常<一个href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception.aspx"><$c$c>TaskScheduler.UnobservedTaskException,这要是未处理将终止该进程。

在.NET 4.5,这行为已更改。现在,未观察到的异常,可以传递给 TaskScheduler.UnobservedTaskException ,但随后他们如果未处理忽略。

Let's say I have three tasks, a, b, and c. All three are guaranteed to throw an exception at a random time between 1 and 5 seconds. I then write the following code:

await Task.WhenAny(a, b, c);

This will ultimately throw an exception from whichever task faults first. Since there's no try...catch here, this exception will bubble up to some other place in my code.

What happens when the remaining two tasks throw an exception? Aren't these unobserved exceptions, which will cause the entire process to be killed? Does that mean that the only way to use WhenAny is inside of a try...catch block, and then somehow observe the remaining two tasks before continuing on?

Follow-up: I'd like the answer to apply both to .NET 4.5 and .NET 4.0 with the Async Targeting Pack (though clearly using TaskEx.WhenAny in that case).

解决方案

What happens when the remaining two tasks throw an exception?

Those Tasks will complete in a faulted state.

Aren't these unobserved exceptions, which will cause the entire process to be killed?

Not anymore.

In .NET 4.0, the Task destructor would pass its unobserved exception to TaskScheduler.UnobservedTaskException, which would terminate the process if unhandled.

In .NET 4.5, this behavior was changed. Now, unobserved exceptions get passed to TaskScheduler.UnobservedTaskException, but then they are ignored if unhandled.

这篇关于Task.WhenAny和不可观测异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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