Why does my c# Windows service stop running without any messages being written to the application event log?

oscilatingcretin picture oscilatingcretin · May 21, 2012 · Viewed 9.4k times · Source

I am fairly new to Windows services. I created an installer for my c# Windows service and the installation on the server (Windows Server 2003) appears to have worked. When it's started, it writes Service started successfully to the log. When it's stopped, it writes Service stopped successfully. However, sometimes the service stops running without writing anything to the log, so I start it back up manually. When I look at the log afterward, it says Service started successfully as expected. It's weird seeing that in the log twice in a row being that it's obviously missing an entry where the service had somehow stopped running.

What could be the potential causes for this? I have the service set up as automatic and installed it to run for all users. I was under the impression that this means the service starts automatically whenever the machine boots up. How can I find out why it stopped? Do services that crash automatically write to the event log or do I have to handle exceptions in such a way that they log their own reason for the crash?

Edit: Some additional info:

  • I have it set up to log on as Local System Account
  • Under Recovery options, I have it set up to restart on first failure. I don't have anything for second or subsequent failures.

Update: An answerer recommended a global exception handler. While I won't implement this as a permanent fix, it will at least help me figure out where the problem is occurring. I actually tested this with my installed service and it works. I found out that unhandled exceptions actually do crash the service without writing anything to the log at all. I thought it'd at least report some application error, but it doesn't.

static void Main()
{
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    //other code here
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Utilities.WriteIt(e.ExceptionObject as Exception);
}

Answer

MichelZ picture MichelZ · May 21, 2012

It's always best to handle the exceptions. At least use a global exception handler and write it to a logfile