Search code examples
c#windows-services

Windows service will not start (Error 1053)


I have a Windows Service that I am trying to debug. Now it fails to start even though the current code used to work. The error is:

Windows could not start the MyService service on Local Computer

Error 1053: The service did not respond to the start or control request in a timely fashion.

To isolate the error, I tried to comment out everything. The main method looks like this:

TextWriter tt = new StreamWriter(@"C:\startup.text", true);
tt.WriteLine("Starting up the service");
tt.Close();

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
   { 
       new MyService()
   };

TextWriter tt2 = new StreamWriter(@"C:\startup.text", true);
tt2.WriteLine("Run...");
tt2.Close();

It prints out both "Starting up the service" and "Run..." to the log file. I also stripped the inside of MyService so it's empty. There is a try/catch around any code, which now is reduced to some log lines like above. I never enters the catch statement, which would have logged it.

Everything in OnStart has been commented out:

protected override void OnStart(string[] args)
{
}

So I'm basically out of ideas. I thought the error was because the Start method never finishes (or doesn't within 30 seconds). Is there some other method that is called? Any ideas are appreciated.

Extra info: The constructor in MyService is empty. If I insert some Thread.Sleep(5000) lines, then it takes longer beofre the error message about Error 1053 pops up. The Main method seems to have to exit (without error).


Solution

  • You are missing ServiceBase.Run call:

    ServiceBase[] servicesToRun = new ServiceBase[]
                                    { 
                                        new MyService() 
                                    };
    ServiceBase.Run(servicesToRun);
    

    It might also be a good idea to subscribe to unhandled exceptions notification:

    static void Main() {
        ...
        AppDomain.CurrentDomain.UnhandledException 
                                          += CurrentDomain_UnhandledException;
        ...
    }
    
    private static void CurrentDomain_UnhandledException(
                                                     Object sender, 
                                                     UnhandledExceptionEventArgs e) {
    
        if (e != null && e.ExceptionObject != null) {
            // log exception:
        }
    }
    

    And add following try/catch to OnStart because .NET/SCM swallows exceptions:

    protected override void OnStart(String[] args) {
        try {
    
        } catch(Exception e) {
            // log exception:
            throw;
        }
    }