简体   繁体   English

Windows Service应用程序中未处理的异常

[英]unhandled exception in windows service application

I would like to catch unhandled exceptions in a windows service application in the class that inherits from ServiceBase class. 我想在Windows Service应用程序中从ServiceBase类继承的类中捕获未处理的异常。 I have already tried incorporating the code: 我已经尝试合并代码:

AppDomain.CurrentDomain.UnhandledException += (s, e) =>
        {
            var exception = (Exception)e.ExceptionObject;
            Log.Error("Unhandled exception", exception);
        };

But that doesn't work. 但这是行不通的。

Try this: 尝试这个:

// Starts the application. 
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
    // Add the event handler for handling non-UI thread exceptions to the event. 
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    // Runs the application.
    Application.Run(new ErrorHandlerForm());
}

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";

        // Since we can't prevent the app from terminating, log this to the event log.
        if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        try
        {
            MessageBox.Show("Fatal Non-UI Error",
                "Fatal Non-UI Error. Could not write the error to the event log. Reason: "
                + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
}

You also can take a look at this example: https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx 您还可以查看以下示例: https : //msdn.microsoft.com/zh-cn/library/system.windows.forms.application.threadexception.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM