How can I restart a windows service programmatically in .NET

后端 未结 10 1114
青春惊慌失措
青春惊慌失措 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 18:41

    You can set a service to restart after failure. So a restart can be forced by throwing an exception.

    Use recovery tab on service properties.

    Be sure to use reset fail count property to prevent service stopping altogether.

    0 讨论(0)
  • 2020-12-02 18:49

    Call Environment.Exit with an error code greater than 0, which seems appropriate, then on install we configure the service to restart on error.

    Environment.Exit(1);
    

    I have done same thing in my Service. It is working fine.

    0 讨论(0)
  • 2020-12-02 18:50

    How about

    var theController = new System.ServiceProcess.ServiceController("IISAdmin");
    
    theController.Stop();
    theController.Start();
    

    Don't forget to add the System.ServiceProcess.dll to your project for this to work.

    0 讨论(0)
提交回复
热议问题