C# 避免在Winforms应用程序中的另一个线程出现未处理的异常时终止应用程序
有人知道当另一个线程发生未处理的异常时,如何防止应用程序终止吗?似乎执行C# 避免在Winforms应用程序中的另一个线程出现未处理的异常时终止应用程序,c#,multithreading,winforms,C#,Multithreading,Winforms,有人知道当另一个线程发生未处理的异常时,如何防止应用程序终止吗?似乎执行AppDomain.CurrentDomain.UnhandledException+=CurrentDomain\u UnhandledException只是在错误发生时捕获,但它不会处理它--我的意思是它不会清除错误,因此错误将继续 以下是我的解决方法: using System; using System.Security.Permissions; using System.Threading; using Syste
AppDomain.CurrentDomain.UnhandledException+=CurrentDomain\u UnhandledException
只是在错误发生时捕获,但它不会处理它--我的意思是它不会清除错误,因此错误将继续
以下是我的解决方法:
using System;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
class ErrorForm : Form {
private Button button2;
Thread newThread = null;
private ErrorForm() {
InitializeComponent();
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args) {
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.Run(new ErrorForm());
}
// Start a new thread, separate from Windows Forms, that will throw an exception.
private void button2_Click(object sender, EventArgs e) {
newThread = new Thread(() => {
throw new Exception("Aha!");
});
newThread.Start();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
MessageBox.Show("CurrentDomain_UnhandledException");
}
private void InitializeComponent() {
this.button2 = new Button();
this.SuspendLayout();
//
// button2
//
this.button2.Location = new System.Drawing.Point(12, 12);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(260, 23);
this.button2.TabIndex = 1;
this.button2.Text = "Make Error";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += this.button2_Click;
//
// ErrorHandlerForm
//
this.ClientSize = new System.Drawing.Size(284, 52);
this.Controls.Add(this.button2);
this.Name = "ErrorHandlerForm";
this.ResumeLayout(false);
}
}
}
当我运行这段代码并按下按钮2时,会按预期调用CurrentDomain\u UnhandledException
,但接下来它会再次返回到抛出新异常(“Aha!”)代码>。我能做的最好的事情就是在方法CurrentDomain\u UnhandledException
中终止进程,如下所示:
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
MessageBox.Show("CurrentDomain_UnhandledException");
if (e.IsTerminating) {
Process.GetCurrentProcess().Kill();
}
}
但这在我的应用程序场景中是不可接受的。我希望应用程序(主窗体)保持活动状态,并顺利处理此错误。我不想用BackgroundWorker
替换Thread
完成的逻辑。可能吗?有什么好的解决办法吗
提前谢谢你 你说它总是回来是什么意思?你是说调试器吗?我知道在旧版本的Visual Studio中,调试器有时会卡住,并不断为同一个异常重复弹出异常助手。是的,它在调试器上——但当我在“CurrentDomain_UnhandledException”消息框显示应用程序崩溃后,在调试器外(CTRL+F5)执行应用程序时。这[1]我的问题解决了。[1] :嗯。。上面的答案是有效的,但不适用于调试器。在抛出异常的线程中捕获并处理异常,而不是等待它退出线程并使程序的其余部分处于危险中,怎么样?