c# - 处理Winforms中的所有线程异常

标签 c# multithreading winforms

我有以下测试代码,

 private void button3_Click(object sender, EventArgs e)
    {
        Thread obj = new Thread(exception);
        obj.Start();
    }
    void exception()
    {
        try
        {
            int i = 0;
            int k = i / i;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void button4_Click(object sender, EventArgs e)
    {
        int i = 0;
        int k = i / i;
    }

我的主要代码是这样的

 [STAThread]
    static void Main()
    {
        Application.ThreadException += Form1_UIThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show("Exception");
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
       // MessageBox.Show("Exception UI");
    }

即使我已经处理了这两个异常,应用程序也会因线程异常而崩溃。

我是否还需要为处理线程异常做任何更正?

最佳答案

您不能处理未处理的 CurrentDomain 异常并让程序在处理后继续。

UnhandledException 事件被引发时,UI 线程的堆栈已经展开太多以至于无法让程序继续。

作为 AppDomain.UnhandledException 的文档状态:

It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

如果您在收到事件通知时检查 e.IsTerminating 的值,您会看到它是 true

您唯一的办法是在按钮处理程序中处理异常。

请注意,在捕获到 ThreadException 后程序可以继续的原因是只有该线程的堆栈已展开,这不会(直接)影响 UI 线程。

关于c# - 处理Winforms中的所有线程异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41586959/

相关文章:

c# - 用户编辑后数据网格单元格格式不保留?

c# - visual studio c# DataGridView 在排序后保持背景颜色

c++ - 信号处理程序和库工作线程

c# - 多个 Backgroundworkers + C#

.net - 将一个代码段执行限制为4个线程的最低开销方法是什么?

c# - Debug.WriteLine(string, params object[]) 是一种方法,但像类型一样使用

c# - 计算服务区域的最有效方法 Asp.net + SQL Server

C# 比 C++ 运行得更快?

c# - Windows 窗体 : Progress Bar Unresponsive

c# - 在 Azure IIS 上的 C# Web 应用程序中使用客户端证书