gpt4 book ai didi

c# - 未在全局处理程序中捕获/处理 ContinueWith 中引发的未处理异常

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:34 24 4
gpt4 key购买 nike

我的应用程序有全局异常处理程序(好吧,记录器,我知道他们在技术上不“处理”它们),它们就像:

public static class UnhandledExceptionHandler
{
public static void Init()
{
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainOnUnhandledException;

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += ApplicationOnThreadException;
}

private static void ApplicationOnThreadException(object sender, ThreadExceptionEventArgs e)
{
if (e.Exception != null)
MessageBox.Show(e.Exception.ToString());
}

private static void OnCurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;

if (ex != null)
MessageBox.Show(ex.ToString());
}
}

Main()中是

UnhandledExceptionHandler.Init();

但我发现当 Task.ContinueWith 中发生未处理的异常时,不会引发这些事件。 Visual Studio 将它们识别为未处理,因为它们在调试器中突出显示。

例如,您可以简单地测试它:

private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => { })
.ContinueWith(t =>
{
throw new Exception("continue with exception");
});
}

您会注意到没有引发 MessageBox(也没有引发任何事件)。

为了证明它确实有效,以下将起作用:

private void button2_Click(object sender, EventArgs e)
{
throw new Exception("click failed");
}

有人知道我为什么和/或如何能够捕获并记录这些未处理的异常吗?

当然,我很欣赏将 ContinueWith 中的逻辑量保持在最低限度可能是有意义的,但它仍然可能发生。

当前是 .NET 4.0

最佳答案

来自评论:

It's a shame though that I have to append a ContinueWith with OnlyOnFaulted to a Task after any other ContinueWiths in order to ensure I handle exceptions.

你不必。只需使用来自 "Processing Sequences of Asynchronous Operations with Tasks" 的 Stephen Toub 的 Then 模式。此外,请务必阅读 "Tasks and Unhandled Exceptions" ,这将有助于更好地理解您所看到的行为。

也就是说,如果您使用 VS2012+ 编写代码,您可能需要认真考虑使用 Microsoft.Bcl.Asyncasync/await。这将使您忘记 ContinueWith,并使用自然的 try/catch 来处理异常。

关于c# - 未在全局处理程序中捕获/处理 ContinueWith 中引发的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21879155/

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