c# - 如何正确捕获 WinForms 应用程序中所有未处理的异常

标签 c# .net winforms exception

我想为我的 WinForms 应用程序中任何线程的所有未处理异常设置处理程序方法。我自己不创建任何应用程序域。

根据 UnhandledException文档,我需要通过 Application.SetUnhandledExceptionMode 方法设置 UnhandledExceptionMode.ThrowException 模式来捕获主线程的异常:

In applications that use Windows Forms, unhandled exceptions in the main application thread cause the Application.ThreadException event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. In that case, the UnhandledException event is not raised. This behavior can be changed by using the application configuration file, or by using the Application.SetUnhandledExceptionMode method to change the mode to UnhandledExceptionMode.ThrowException before the ThreadException event handler is hooked up. This applies only to the main application thread. The UnhandledException event is raised for unhandled exceptions thrown in other threads

因此,生成的代码将如下所示:

    public static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
    {
        // ...
    }

    [STAThread]
    static void Main(string[] args)
    {
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm(pathToCheck));
    }

还好吗?它会捕获来自任何线程(包括主线程、UI 线程和所有由 Task 类创建的线程)的所有未处理的异常吗?我是否正确理解了文档?

是的,我看到了类似 this 的问题在这里,但我不明白为什么还要使用以下代码:

Application.ThreadException += new     
  ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

最佳答案

您应该订阅这两个事件。请注意,即使这样也不会自动捕获来自其他线程的所有内容。例如,当异步调用委托(delegate)时,只有在调用 EndInvoke 时异常才会传播到调用者线程。

    [STAThread]
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException +=
            (sender, args) => HandleUnhandledException(args.ExceptionObject as Exception);
        Application.ThreadException +=
            (sender, args) => HandleUnhandledException(args.Exception);
    }

    static void HandleUnhandledException(Exception e)
    {
        // show report sender and close the app or whatever
    }

关于c# - 如何正确捕获 WinForms 应用程序中所有未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32394179/

相关文章:

c# - 如何将十进制(整数)转换为二进制,使用二进制,然后在 C# 中将其转换回十进制

c# - 正则表达式匹配未完成

c# - 如何获取 HttpResponseHeader 的名称?

c# - 如何在.net、C# 中为 Orientdb 编写 "UPSERT"查询?

c# - 永久类型转换到父类(super class)

c# - 使用 C# 或在 C# 中的 native C++ 性能

c# - C# API 错误和异常处理的最佳实践

c# - 关注应用程序 - 与操作系统相关的问题?

c# - winforms .Net 关于小方法的使用

c# - 调用 OpenFileDialog.ShowDialog() 时 Windows 窗体 GUI 挂起