我有以下测试代码,
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/