捕获未处理的异常,仍然显示"程序停止工作"对话框

Izi*_*kon 5 c# exception unhandled-exception winforms

在这篇文章中读过,为了避免"程序停止工作"对话框,我需要从AppDomain中捕获未处理的异常.

 public Form1()
 {
  ///Code
   AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  ///more code
 }

     void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var excep = e.ExceptionObject;

        //Writing the exception to log file with the stack flow
        Logger.Logger.LogException("UNHANDLED EXCEPTION:"+Environment.NewLine +excep.ToString(), this);

        //Terminate the logger (manual event waiting for file write to finish)
        Logger.Logger.Terminate();
        Environment.Exit(1);
    }
Run Code Online (Sandbox Code Playgroud)

但是当我被吸入异常时.我可以看到它写在日志上,但应用程序显示"程序停止工作"对话框.它可以由Logger.Terminate线路引起吗?(再次 - terminate命令等待,直到所有日志都写入日志文件)

Joã*_*des 0

理想情况下,您希望避免 \xe2\x80\x9cprogram Stopworking\xe2\x80\x9d 对话框,因为您首先希望避免 \xe2\x80\x9cprogram Stopworking\xe2\x80\x9d 情况。如果不是,如果您只想记录错误并让程序优雅地结束,那么程序实际上必须优雅地结束。

\n\n

如果您使用 退出程序Environment.Exit(1),您\xc2\xb4 几乎是在告诉操作系统,“嘿,我窃听了!”,这与优雅终止相反。尝试使用 0 代码退出,看看是否有任何区别。

\n