gpt4 book ai didi

c# - 在 ContinueWith 中观察任务异常

转载 作者:可可西里 更新时间:2023-11-01 08:43:42 26 4
gpt4 key购买 nike

有多种方法可以观察任务中抛出的异常。其中之一在 ContinueWith 和 OnlyOnFaulted 中:

var task = Task.Factory.StartNew(() =>
{
// Throws an exception
// (possibly from within another task spawned from within this task)
});

var failureTask = task.ContinueWith((t) =>
{
// Flatten and loop (since there could have been multiple tasks)
foreach (var ex in t.Exception.Flatten().InnerExceptions)
Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);

我的问题:异常是在 failureTask 开始后自动观察到,还是只有在我“触摸”ex.Message 后才会观察到?

最佳答案

一旦您访问 Exception 属性,它们就会被视为观察到

另请参阅 AggregateException.Handle。您可以改用 t.Exception.Handle:

t.Exception.Handle(exception =>
{
Console.WriteLine(exception);
return true;
}
);

关于c# - 在 ContinueWith 中观察任务异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11743756/

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