private static void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e) { ConsoleControl.SetConsoleIcon(0); Exception ex = e.ExceptionObject as Exception; if (ex != null) { Log("Fatal error. Details:"); Log(ex); EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to a fatal error: " + ex, EventLogEntryType.Error); } else { Log("Fatal error."); EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to a fatal error.", EventLogEntryType.Error); } if (_oldEncoding != null) { Console.OutputEncoding = _oldEncoding; } if (OptionKillOnException) { Process.GetCurrentProcess().Kill(); } }
private static void OnConsoleControlEvent(object sender, ConsoleControlEventArgs e) { if (_service != null) { Log("Service Host console closing."); _service.InternalStop(); int maxWaitTime = Configuration.ConsoleCloseMaxWaitTime; if (maxWaitTime <= 0) { maxWaitTime = Timeout.Infinite; } Log("Service Host console closing. Max wait time: " + ((maxWaitTime == Timeout.Infinite) ? "infinite" : maxWaitTime + " ms")); _closed.WaitOne(maxWaitTime, Configuration.WaitExitContext); } ConsoleControl.SetConsoleIcon(0); if (_oldEncoding != null) { Console.OutputEncoding = _oldEncoding; } Process.GetCurrentProcess().Kill(); }
static void Main(string[] args) { bool newConsole = ConsoleControl.AllocConsole(); ConsoleControl.SetConsoleIcon(ConsoleControl.ApplicationIcon); // we need that early on (for error reporting) OptionName = CommandLineUtilities.GetArgument <string>(args, "name", DefaultName); OptionEncoding = CommandLineUtilities.GetArgument <Encoding>(args, "encoding", null); if (OptionEncoding != null) { _oldEncoding = Console.OutputEncoding; Console.WriteLine("Switching output encoding from '" + _oldEncoding.WebName + "' to '" + OptionEncoding.WebName + "'"); Console.OutputEncoding = OptionEncoding; } _closed = new AutoResetEvent(true); _service = new Program(); _service.AutoLog = false; _service.EventLog.Source = OptionName; SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException; try { SafeMain(args); } catch (Exception e) { bool reported = false; if (_service != null) { try { _service.EventLog.WriteEntry("Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); reported = true; } catch { } } if (!reported) { EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); } EventLog.WriteEntry(OptionName, "Service Host '" + OptionName + "' was stopped due to an error: " + e, EventLogEntryType.Error); Log("Fatal error. Details:"); Log(e); } if (_oldEncoding != null) { Console.OutputEncoding = _oldEncoding; } if (newConsole) { ConsoleControl.FreeConsole(); } ConsoleControl.SetConsoleIcon(0); }