Task.WhenAny 和未观察到的异常 [英] Task.WhenAny and Unobserved Exceptions
问题描述
假设我有三个任务,a
、b
和 c
.所有三个都保证在 1 到 5 秒之间的随机时间抛出异常.然后我写了下面的代码:
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);
这最终会从首先出现故障的任务中抛出异常.由于这里没有 try...catch
,这个异常会冒泡到我代码中的其他地方.
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.
当剩下的两个任务抛出异常时会发生什么?这些不是观察不到的异常,会导致整个进程被杀死吗?这是否意味着使用 WhenAny
的唯一方法是在 try...catch
块内,然后在继续之前以某种方式观察剩余的两个任务?
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?
跟进:我希望答案适用于 .NET 4.5 和 .NET 4.0 和 Async Targeting Pack(虽然显然使用 TaskEx.WhenAny
在那种情况下).
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?
那些Task
将在错误状态下完成.
Those Task
s will complete in a faulted state.
这些不是观察不到的异常,会导致整个进程被杀死吗?
Aren't these unobserved exceptions, which will cause the entire process to be killed?
没有了.
在 .NET 4.0 中,Task
析构函数会将其未观察到的异常传递给 TaskScheduler.UnobservedTaskException
,如果未处理将终止进程.
In .NET 4.0, the Task
destructor would pass its unobserved exception to TaskScheduler.UnobservedTaskException
, which would terminate the process if unhandled.
在 .NET 4.5 中,此行为已更改.现在,未观察到的异常被传递给 TaskScheduler.UnobservedTaskException
,但如果未处理,它们将被忽略.
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屋!