c#console应用程序 - 防止默认异常对话框

But*_*aur 7 c# dialog exception-handling console-application

我有单个AppDomain的简单应用程序,它在服务器上定期启动.有时在应用程序中发生未处理的异常,弹出默认的中止/重试/忽略对话框.我需要以某种方式阻止edialog显示并在StrErr上输出异常并关闭应用程序.所以我用try-catch语句将main方法中的所有代码都包含在内,但它根本没有帮助 - 有时候仍会显示异常对话框.

Main()代码如下所示:

try
{
    RunApplication();
}
catch (Exception exc)
{   
    Console.Error.WriteLine(exc.ToString());
    Console.Error.WriteLine(exc.StackTrace);
    if (exc.InnerException != null)
    {
       Console.Error.WriteLine(exc.InnerException.ToString());
       Console.Error.WriteLine(exc.InnerException.StackTrace);
    }
    Environment.Exit(666);
}
Run Code Online (Sandbox Code Playgroud)

这个try-catch子句可以捕获所有未处理的异常,异常对话框永远不会弹出AFAIK.我错过了什么吗?或者服务器上是否有任何设置(注册表等)控制与异常对话框/应用程序错误代码相关的一些特殊行为?

Rei*_*ica 20

您可以在应用程序域中订阅未处理的异常事件.

    public static void Main()   
    {   
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

        //some code here....
    }   

    /// <summary>
    /// Occurs when you have an unhandled exception
    /// </summary>
    public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)   
    { 
        //here's how you get the exception  
        Exception exception = (Exception)e.ExceptionObject;  

        //bail out in a tidy way and perform your logging
    }
Run Code Online (Sandbox Code Playgroud)