gpt4 book ai didi

c# - 在出现 OnlyOnFaulted 时使用 TPL 时出现未处理的异常

转载 作者:行者123 更新时间:2023-11-30 22:21:00 26 4
gpt4 key购买 nike

这是“C# 5.0 in a Nutshell”中的示例代码

TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
Task.Factory.StartNew (() =>
{
Task.Factory.StartNew (() => { throw null; }, atp);
Task.Factory.StartNew (() => { throw null; }, atp);
Task.Factory.StartNew (() => { throw null; }, atp);
})
.ContinueWith (p => Console.WriteLine (p.Exception),
TaskContinuationOptions.OnlyOnFaulted);

我有一个“CLR 异常”:在我的 VS2012 设置中选中了“在用户未处理时中断”选项,运行此代码会在 throw null;< 上提供 VS 的“用户代码未处理 NRE 异常”弹出窗口

我已经尝试在 ContinueWith 和稍后的 Wait 上 try catch 异常,但仍然遇到未处理的异常。

我觉得关闭“CLR 异常”的解决方案:“中断用户未处理”似乎是错误的,因为我实际上处理了这个异常。那么怎样才是正确的管理方式呢?

最佳答案

调试器停止执行的原因是“Break on user-unhandled exceptions”将 break on any exception that is not handled by a handler in user code ("My Code").

因为捕获异常的 TPL 是 not considered user code ,调试器将考虑用户代码未处理的异常。

问题是,TPL 没有任何其他方式来触发 TaskContinuationOptions.OnlyOnFaulted ,所以恐怕您可能无法看到异常。

希望获得异常不是您正常流程的一部分。如果不是,在调试器中看到未处理的异常对于调试任务流中的错误实际上可能是一件好事。

关于c# - 在出现 OnlyOnFaulted 时使用 TPL 时出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670522/

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