gpt4 book ai didi

c# - 使用 TPL 时未触发异常

转载 作者:行者123 更新时间:2023-11-30 21:37:44 25 4
gpt4 key购买 nike

我有以下代码不会触发 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/

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