Dot-Net

AppDomain.CurrentDomain.UnhandledException 在沒有調試的情況下不會觸發

  • April 18, 2021

我有一個帶有綁定到 Application.CurrentDomain.UnhandledException 的事件處理程序的 .NET 程序。執行帶有調試的程序時,當拋出未處理的異常時會觸發此事件。但是,在沒有調試的情況下執行時,事件不會觸發。

我的問題是什麼?

謝謝,安德魯

我假設您沒有使用 - 設置正確的異常處理模式Application.SetUnhandledExceptionMode()- 只需將其設置為UnhandledExceptionMode.ThrowException.

更新

我剛剛編寫了一個小型測試應用程序,並沒有發現任何可以正常工作的東西。您可以嘗試使用此測試程式碼重現您的錯誤嗎?

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication
{
   public static class Program
   {
       static void Main()
       {
           AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;

           Application.ThreadException += Application_ThreadException;
           Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

           Application.Run(new TestForm());

           throw new Exception("Main");
       }

       static void Application_ThreadException(Object sender, ThreadExceptionEventArgs e)
       {
           MessageBox.Show(e.Exception.Message, "Application.ThreadException");
       }

       static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
       {
           MessageBox.Show(((Exception)e.ExceptionObject).Message, "AppDomain.UnhandledException");
       }
   }

   public class TestForm : Form
   {
       public TestForm()
       {
           this.Text = "Test Application";
           this.ClientSize = new Size(200, 60);
           this.MinimumSize = this.Size;
           this.MaximumSize = this.Size;
           this.StartPosition = FormStartPosition.CenterScreen;

           Button btnThrowException = new Button();

           btnThrowException.Text = "Throw";
           btnThrowException.Location = new Point(0, 0);
           btnThrowException.Size = new Size(200, 30);
           btnThrowException.Click += (s, e) => { throw new Exception("Throw"); };

           Button btnThrowExceptionOnOtherThread = new Button();

           btnThrowExceptionOnOtherThread.Text = "Throw on other thread";
           btnThrowExceptionOnOtherThread.Location = new Point(0, 30);
           btnThrowExceptionOnOtherThread.Size = new Size(200, 30);
           btnThrowExceptionOnOtherThread.Click += (s, e) => new Thread(() => { throw new Exception("Other thread"); }).Start();

           this.Controls.Add(btnThrowException);
           this.Controls.Add(btnThrowExceptionOnOtherThread);
       }
   }
}

引用自:https://stackoverflow.com/questions/1300319