加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

TimeoutException,TaskCanceledException C#

发布时间:2020-12-15 07:58:55 所属栏目:百科 来源:网络整理
导读:我是C#的新手,我发现异常有点令人困惑…… 我有一个带有以下代码的Web应用程序: try{ //do something}catch (TimeoutException t){ Console.WriteLine(t);}catch (TaskCanceledException tc){ Console.WriteLine(tc);}catch (Exception e){ Console.WriteLi
我是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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读