How can I restart a windows service programmatically in .NET

后端 未结 10 1255
青春惊慌失措
青春惊慌失措 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:41

    An example using by ServiceController Class

    private void RestartWindowsService(string serviceName)
    {
        ServiceController serviceController = new ServiceController(serviceName);
        try
        {
            if ((serviceController.Status.Equals(ServiceControllerStatus.Running)) || (serviceController.Status.Equals(ServiceControllerStatus.StartPending)))
            {
                serviceController.Stop();
            }
            serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
            serviceController.Start();
            serviceController.WaitForStatus(ServiceControllerStatus.Running);
        }
        catch
        {
            ShowMsg(AppTexts.Information, AppTexts.SystematicError, MessageBox.Icon.WARNING);
        }
    }
    

提交回复
热议问题