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);
}
}