How can I restart a windows service programmatically in .NET

后端 未结 10 1242
青春惊慌失措
青春惊慌失措 2020-12-02 18:21

How can I restart a windows service programmatically in .NET?
Also, I need to do an operation when the service restart is completed.

10条回答
  •  死守一世寂寞
    2020-12-02 18:38

    This article uses the ServiceController class to write methods for Starting, Stopping, and Restarting Windows services; it might be worth taking a look at.

    Snippet from the article (the "Restart Service" method):

    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
      {
        // ...
      }
    }
    

提交回复
热议问题