【发布时间】:2015-08-04 20:22:18
【问题描述】:
当我使用Task.WhenAll() 函数并在任务中引发异常时,会引发新的 AggregateException,我可以捕获它以查看任务中发生的所有异常。但是,当我使用 Task.WhenAny() 时,不会引发异常。相反,我必须检查Task.Exception 属性的值,以查看是否发生异常。这似乎是一种糟糕的代码气味,因为我必须记住每次使用Task.WhenAny() 时都要检查Task.Exception 属性。不应该有更好的方法吗?
这是我的意思的一个例子:
private async void btnMultipleExceptions_Click(object sender, EventArgs e) {
var task1 = ThrowNotImplementedException();
var task2 = ThrowDivideByZeroException();
try {
Task task = await Task.WhenAny(task1, task2);
// Even if an exception is thrown in one of the tasks (in our case,
// task1 will throw first) no exception is thrown from
// the above await Task.WhenAny(). Instead, the exception is placed on the
// Task.Exception property. So I need to check for it every time
// I call Task.WhenAny()?
if (task.Exception != null) {
Console.WriteLine("Exceptions: " + string.Join(Environment.NewLine,
task.Exception.InnerExceptions.Select(x => x.Message).ToArray()));
} else {
Console.WriteLine("No Exceptions!");
}
} catch(Exception ex) {
// Try to catch all exceptions???
AggregateException allEx = ex as AggregateException;
if (allEx != null) {
Console.WriteLine("Exceptions: " + string.Join(Environment.NewLine,
allEx.InnerExceptions.Select(x => x.Message).ToArray()));
} else {
Console.WriteLine("Exceptions: " + ex.Message);
}
}
}
private async Task ThrowNotImplementedException() {
await Task.Delay(TimeSpan.FromSeconds(1));
throw new NotImplementedException();
}
private async Task ThrowDivideByZeroException() {
await Task.Delay(TimeSpan.FromSeconds(2));
throw new DivideByZeroException();
}
【问题讨论】:
标签: c# .net async-await task-parallel-library c#-5.0