2016-12-27 83 views
0

我想从继承自ServiceBase类的类中的窗口服务应用程序中捕获未处理的异常。 我已经尝试引入代码:窗口服务应用程序中未处理的异常

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

但是,这并不工作。

+0

的[在一个窗口服务未处理的异常(可能的复制http://stackoverflow.com/questions/ 10609443 /未处理的例外-IN-A-Windows的服务) –

回答

0

试试这个:

// 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(); 
     } 
    } 
} 

您也可以看看这个例子:https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx