Search code examples
windowsservicerestart

Windows Service - Restart itself?


I need to put some code to restart my Windows Service when faces a critical error (big story)

I have this function

public Boolean RestartService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);
        try
        {
            int millisec1 = Environment.TickCount;
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            int millisec2 = Environment.TickCount;
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            if (service.Status != ServiceControllerStatus.Running)
            {
                return false;
            }
        }
        catch (System.ServiceProcess.TimeoutException ex)
        {

            return false;
        }
        return true;
    }

The thing is that it is obviously not good because although it Stops...it cannot Start again :)

Is there a way to re-construct it in such way that it can "remember" to Start itself?

Thanx!


Solution

  • When a service is stopped it is stopped. It doesn't run anymore, so no more code is being executed.

    There in my opinion two ways you can achieve this: Windows is able to re-start services upon fatal errors itself. All you need to do is the following:

    Set the service to restart after failure (double click the service in the control panel). If you want the service to restart, just call Environment.Exit(1); (or any non-zero return) and the OS will restart it for you.

    Another way would be to write a service monitor service that checks whether the service is stopped and then restarts it.