我有以下代码,它不会引发 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)
{ }
}
}
最佳答案
这是因为您正在等待继续任务(运行 Test2()
)的完成,而不是等待运行 Test()
的任务完成。第一个任务因异常而失败,然后后续任务对此异常不执行任何操作(您不检查 previousTask
是否失败)并成功完成。要捕获该异常,您需要等待第一个任务或继续检查它的结果:
var task1 = Task.Factory.StartNew(() =>
{
Test();
});
var task2 = task1.ContinueWith((previousTask) =>
{
Test2();
});
或
var task1 = Task.Factory.StartNew(() =>
{
Test();
}).ContinueWith((previousTask) =>
{
if (previousTask.Exception != null) {
// do something with it
throw previousTask.Exception.GetBaseException();
}
Test2();
}); // note that task1 here is `ContinueWith` task, not first task
当然,这与您是否真的应该这样做无关,只是为了回答问题。
关于c# - 使用 TPL 时不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46955238/