2016-12-27 1 views
0

Ich möchte nicht behandelte Ausnahmen in einer Windows-Dienstanwendung in der Klasse abfangen, die von der ServiceBase-Klasse erbt. Ich habe bereits versucht, den Code enthält:unbehandelte Ausnahme in Windows-Dienstanwendung

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

Aber das funktioniert nicht.

+0

Mögliche Duplikat [unbehandelte Ausnahmen in Windows-Dienst] (http://stackoverflow.com/questions/ 10609443/Unbehandelte-Ausnahmen-in-einem-Windows-Dienst) –

Antwort

0

Versuchen Sie folgendes:

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

Sie können auch einen Blick auf dieses Beispiel nehmen: https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx

Verwandte Themen