title: Restart Windows Service in c#
body: <p>I got a link from SO <a href="https://stackoverflow.com/questions/3309990/cannot-restart-a-service-c">Cannot restart a Service</a> where it says to restart the windows service.</p>
  
  <p>The way it should restart the service is mentioned in the question as </p>
  
  <pre><code>public static void RestartService(string serviceName, int timeoutMilliseconds)
  {
      ServiceController service = new ServiceController(serviceName);
  
      int millisec1 = Environment.TickCount;
      TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
      if (!(service.Status.Equals(ServiceControllerStatus.Stopped) || service.Status.Equals(ServiceControllerStatus.StopPending)))
      {
          service.Stop();
          service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
      }
      // count the rest of the timeout
      int millisec2 = Environment.TickCount;
      timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
  
      if (!(service.Status.Equals(ServiceControllerStatus.Running) || service.Status.Equals(ServiceControllerStatus.StartPending)))
      {
          service.Start();
          service.WaitForStatus(ServiceControllerStatus.Running, timeout);
      }
  }
  </code></pre>
  
  <p>But i am not sure here, as to where to write the code. I need to restart the windows service as soon as that is installed from my application</p>
  
  <p>Let me know if any input is needed.</p>
  
  <p>Thanks!</p>