Windows service exception not handled

I have a regular C # service based on the ServiceBase class. This service loads when the C ++ dynamic link library starts. Sometimes it happens that the service fails in unmanaged code. Unfortunately, Event Viewer gives only a very brief description of this. It looks like one if his message:

Application: StreamMapService.exe Framework version: v4.0.30319 Description: The process was aborted due to an unhandled exception. Exception information: exception code c0000005, exception address 00000012 ".

With 99% confidence, the problem is in unmanaged code. The problem is that this happens very rarely (usually once a day) and only when the service starts. Everything is fine in the debugger. To find out the problematic code, I edited my main method as follows:

    static void Main()
    {
        try
        {
            if (!Environment.UserInteractive)
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                var services = new Service1();
                services.Start();
                Console.WriteLine("Press return to exit");
                Console.ReadLine();
                services.Stop();
            }
        }
        catch (SEHException e)
        {
            // wrapper for all exceptions having its origin in unmanaged code
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Crash time: {0}\n", DateTime.Now.ToString());
            sb.AppendFormat("\nMessage:\n{0}", e.Message);
            sb.AppendFormat("\nSource: {0}\n", e.Source);
            sb.AppendFormat("Stack trace:\n{0}", e.StackTrace);
            sb.AppendFormat("\nTarget site:{0}", e.TargetSite);

            SmtpClient client = new SmtpClient("mail.domain.com");
            MailAddress from = new MailAddress("sender@domain.com", "sender", System.Text.Encoding.UTF8);
            MailAddress to = new MailAddress("receiver@domain.com");
            MailMessage message = new MailMessage(from, to);
            message.Body = sb.ToString();
            message.Subject = "StreamMapService crash info";
            client.Send(message);
            throw;
        }
    }

, . , .

( , , ).

( → "" → "" ), ( tcp-, ), .

, . , .

, . . , .

+3
1

, , . , :

AppDomain.CurrentDomain.UnhandledException += 
  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

:

void CurrentDomain_UnhandledException(
    object sender, UnhandledExceptionEventArgs e) {
}
+1

Source: https://habr.com/ru/post/1787636/


All Articles