How can I restart a windows service programmatically in .NET

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

    This answer is based on @Donut Answer (the most up-voted answer of this question), but with some modifications.

    1. Disposing of ServiceController class after each use, because it implements IDisposable interface.
    2. Reduce the parameters of the method: there is no need to the serviceName parameter being passed for each method, we can set it in the constructor, and each other method will use that service name.
      This is also more OOP friendly.
    3. Handle the catch exception in a way that this class could be used as a component.
    4. Remove the timeoutMilliseconds parameter from each method.
    5. Add two new methods StartOrRestart and StopServiceIfRunning, which could be considered as a wrapper for other basic methods, The purpose of those methods are only to avoid exceptions, as described in the comment.

    Here is the class

    public class WindowsServiceController
    {
        private string serviceName;
    
        public WindowsServiceController(string serviceName)
        {
            this.serviceName = serviceName;
        }
    
        // this method will throw an exception if the service is NOT in Running status.
        public void RestartService()
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                try
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
    
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Can not restart the Windows Service {serviceName}", ex);
                }
            }
        }
    
        // this method will throw an exception if the service is NOT in Running status.
        public void StopService()
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                try
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Can not Stop the Windows Service [{serviceName}]", ex);
                }
            }
        }
    
        // this method will throw an exception if the service is NOT in Stopped status.
        public void StartService()
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                try
                {
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Can not Start the Windows Service [{serviceName}]", ex);
                }
            }
        }
    
        // if service running then restart the service if the service is stopped then start it.
        // this method will not throw an exception.
        public void StartOrRestart()
        {
            if (IsRunningStatus)
                RestartService();
            else if (IsStoppedStatus)
                StartService();
        }
    
        // stop the service if it is running. if it is already stopped then do nothing.
        // this method will not throw an exception if the service is in Stopped status.
        public void StopServiceIfRunning()
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                try
                {
                    if (!IsRunningStatus)
                        return;
    
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Can not Stop the Windows Service [{serviceName}]", ex);
                }
            }
        }
    
        public bool IsRunningStatus => Status == ServiceControllerStatus.Running;
    
        public bool IsStoppedStatus => Status == ServiceControllerStatus.Stopped;
    
        public ServiceControllerStatus Status
        {
            get
            {
                using (ServiceController service = new ServiceController(serviceName))
                {
                    return service.Status;
                }
            }
        }
    }
    

提交回复
热议问题