Task.WhenAny和不可观测异常异常、Task、WhenAny

由网友(怕媳妇不是软弱那是爱i)分享简介:让我们说我有三个任务, A , B 和 C 。所有三个都保证在1和5秒之间的随机时间抛出异常。然后我写了下面的code:等待Task.WhenAny(A,B,C);这最终将首先抛出从哪个任务故障异常。由于没有的try ... catch 在这里,这个异常会冒泡到其他地方在我的code。在剩下的两个任务抛出一个异常,会发...

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

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

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

对于 C 中 Task 的 StartNew 与 WhenAll 相互配合的实验

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

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

解决方案   

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

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

  

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

现在不一样了。

在.NET 4.0中,工作的析构函数将通过其未观测到的异常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.

阅读全文

相关推荐

最新文章