TimeoutException,TaskCanceledException C#

前端之家收集整理的这篇文章主要介绍了TimeoutException,TaskCanceledException C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是C#的新手,我发现异常有点令人困惑……
我有一个带有以下代码的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还是会捕获异常?这是为什么?

解决方法

捕获异常时,您必须确保它正是抛出的异常.当使用Task.Run或Task.Factory.Startnew并且通常涉及从任务抛出异常时(除非正在等待使用 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);
}
原文链接:https://www.f2er.com/csharp/100187.html

猜你在找的C#相关文章