gpt4 book ai didi

c# - TimeoutException、TaskCanceledException C#

转载 作者:太空狗 更新时间:2023-10-29 20:23:52 28 4
gpt4 key购买 nike

我是 C# 的新手,我发现异常有点令人困惑...我有一个包含以下代码的网络应用程序:

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 还是也会捕获 Exception?这是为什么?

最佳答案

捕获Exception 时,您必须确保它正是 被抛出的异常。当使用 Task.RunTask.Factory.Startnew 并且通常涉及从 Task 抛出异常时(除非正在等待任务await 关键字),您正在处理的外部异常是 AggregateException ,因为 Task 单元可能有子任务,这些子任务也可能抛出异常。

来自 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);
}

关于c# - TimeoutException、TaskCanceledException C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24866455/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com