【发布时间】:2017-10-26 21:22:58
【问题描述】:
我有以下代码不会触发 AggregateException 未触发聚合异常,我不明白为什么?通常它应该作为聚合异常用于在使用任务运行代码时捕获异常
class Program
{
static void Main(string[] args)
{
var task1 = Task.Factory.StartNew(() =>
{
Test();
}).ContinueWith((previousTask) =>
{
Test2();
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
// Handle the custom exception.
if (e is CustomException)
{
Console.WriteLine(e.Message);
}
// Rethrow any other exception.
else
{
throw;
}
}
}
}
static void Test()
{
throw new CustomException("This exception is expected!");
}
static void Test2()
{
Console.WriteLine("Test2");
}
}
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
}
【问题讨论】:
-
确定不是调试器在您的代码有机会之前捕获它?
-
即使我不使用调试器也会出现同样的问题。我没有收到
This exception is expected -
我认为是因为您使用了 StartNew,因为在代码尝试等待之前发生了错误
-
这就是为什么您应该真正使用
await而不是使用ContinueWith手动添加延续。await的最大优势之一是它以大多数人期望的方式传播异常,这与ContinueWith不同。
标签: c# .net task-parallel-library