我有一个带有以下代码的Web应用程序:
try { //do something } catch (TimeoutException t) { Console.WriteLine(t); } catch (TaskCanceledException tc) { Console.WriteLine(tc); } catch (Exception e) { Console.WriteLine(e); }
当我调试代码时,它抛出了e Exception,这是最常见的,当我将鼠标悬停在异常信息上时,它发现它是TaskCanceledException.为什么没有捕获TaskCanceledException?如果异常是TimeoutException,它会捕获TimeoutException还是会捕获异常?这是为什么?
解决方法
await
关键字的任务),您正在处理的外部异常是
AggregateException
,因为一个任务单元可能有子任务,也可能会抛出异常.
从Exception Handling (Task Parallel Library):
Unhandled exceptions that are thrown by user code that is running
inside a task are propagated back to the joining thread,except in
certain scenarios that are described later in this topic. Exceptions
are propagated when you use one of the static or instance Task.Wait or
Task.Wait methods,and you handle them by enclosing the call
in a try-catch statement. If a task is the parent of attached child
tasks,or if you are waiting on multiple tasks,then multiple
exceptions could be thrown. To propagate all the exceptions back to
the calling thread,the Task infrastructure wraps them in an
AggregateException instance. The AggregateException has an
InnerExceptions property that can be enumerated to examine all the
original exceptions that were thrown,and handle (or not handle) each
one individually. Even if only one exception is thrown,it is still
wrapped in an AggregateException.
所以,为了处理它,你必须捕获AggregateException:
try { //do something } catch (TimeoutException t) { Console.WriteLine(t); } catch (TaskCanceledException tc) { Console.WriteLine(tc); } catch (AggregateException ae) { // This may contain multiple exceptions,which you can iterate with a foreach foreach (var exception in ae.InnerExceptions) { Console.WriteLine(exception.Message); } } catch (Exception e) { Console.WriteLine(e); }