C# .NET - How to Windows Service Restart - Asked By Saravana kumar on 01-Jul-10 09:01 AM


Hi,

I have developed windows service and installed. when i get error , i need to restart the windows service then only it works fine. So Every time i need to restart manually when i got error. How to restart windows service automatically?

Sagar P replied to Saravana kumar on 01-Jul-10 09:05 AM

Check out this simple code to Restart service using c# code;


public static void 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);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}

http://www.csharp-examples.net/restart-windows-service/