To restart a Windows Service we can use the ‘Recovery’ properties as provided by the SCM itself. Just follow the instructions :
From Start Menu go to
–> Control Panel
–> Administrative Tools
–> Services
–> (Select your Service)
Then right click on your service and go to its properties, there you can find the ‘Recovery’ tab. Here you can set the properties for ‘First failure’, ‘Second failure’ etc as specified in the dropdown. Even if after setting these properties, sometimes these doesn’t work properly due to some unhandeled exceptions got from the service’s thread.
However, if an exception is caught we can restart the service even programmatically.
public static void RestartService(string serviceName, int timeoutInterval) { ServiceController service = new ServiceController(serviceName); try { int time1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutInterval); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); int time2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(timeoutInterval - (time1 - time2)); // Count the rest of the timeout service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch(Exception ex) { WriteToLogFile(ex.Message); } }
Another tip which is very essential for all Windows Service developesr who are using EventLog. You need to set properties of the EventLog correctly otherwise it may throw exception while the service is running. To set its properties you can follow this path: Start –> Control Panel –> Administrative Tools –> Event Viewer –> (Select your Service’s EventLog) . Then right click on it and go to its properties. There you need to set the ‘Maximum log size’ field as required in the service and in the ‘When maximum log size is reached’ property you can set to ‘Overwrite events as needed’ this is a recommended one