program story

.NET에서 프로그래밍 방식으로 Windows 서비스를 다시 시작하는 방법

inputbox 2020. 11. 23. 08:04
반응형

.NET에서 프로그래밍 방식으로 Windows 서비스를 다시 시작하는 방법


.NET에서 프로그래밍 방식으로 Windows 서비스를 다시 시작하려면 어떻게해야합니까?
또한 서비스 재시작이 완료되면 작업을해야합니다.


ServiceController 클래스를 살펴보십시오 .

서비스를 다시 시작할 때 수행해야하는 작업을 수행하려면 서비스에서 직접 수행해야합니다 (자신의 서비스 인 경우).
이 서비스의 소스에 액세스 할 수없는 경우, 아마도 당신은 사용할 수 WaitForStatus의 방법을 ServiceController.


이 문서 에서는 ServiceController클래스를 사용하여 Windows 서비스 시작, 중지 및 다시 시작에 대한 메서드를 작성합니다. 살펴볼 가치가 있습니다.

기사의 스 니펫 ( "Restart Service"메소드) :

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

ServiceController 클래스 사용 예

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);
    }
}

net이 작업을 수행하기 위해 명령을 호출 할 수도 있습니다 . 예:

System.Diagnostics.Process.Start("net", "stop IISAdmin");
System.Diagnostics.Process.Start("net", "start IISAdmin");

이 답변은 @Donut 답변 (이 질문에 대해 가장 많이 찬성 된 답변)을 기반으로하지만 약간 수정되었습니다.

  1. 인터페이스를 ServiceController구현하기 때문에 매번 사용 후 클래스 폐기 IDisposable.
  2. 메서드의 매개 변수를 줄 serviceName입니다. 각 메서드에 대해 매개 변수를 전달할 필요가 없으며 생성자에서 설정할 수 있으며 서로 다른 메서드가 해당 서비스 이름을 사용합니다.
    이것은 또한 OOP 친화적입니다.
  3. 이 클래스를 컴포넌트로 사용할 수있는 방식으로 catch 예외를 처리하십시오.
  4. timeoutMilliseconds각 메소드 에서 매개 변수를 제거하십시오 .
  5. 이 새로운 방법 추가 StartOrRestartStopServiceIfRunning주석에 설명 된대로 다른 기본적인 방법의 래퍼로 간주 될 수있다, 이러한 방법의 목적은 피할 예외에만 있습니다.

여기 수업이 있습니다

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;
            }
        }
    }
}

어때

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

theController.Stop();
theController.Start();

이 작업을 수행하려면 System.ServiceProcess.dll을 프로젝트에 추가하는 것을 잊지 마십시오.


기사를 참조 하십시오 .

다음은 기사 의 일부입니다 .

//[QUICK CODE] FOR THE IMPATIENT
using System;
using System.Collections.Generic;
using System.Text;
// ADD "using System.ServiceProcess;" after you add the 
// Reference to the System.ServiceProcess in the solution Explorer
using System.ServiceProcess;
namespace Using_ServiceController{
    class Program{
        static void Main(string[] args){
            ServiceController myService = new ServiceController();
            myService.ServiceName = "ImapiService";
            string svcStatus = myService.Status.ToString();
                if (svcStatus == "Running"){
                    myService.Stop();
                }else if(svcStatus == "Stopped"){
                    myService.Start();
                }else{
                    myService.Stop();
                }
        }
    }
}

Environment.Exit적절 해 보이는 0보다 큰 오류 코드로 호출 한 다음 설치시 오류 발생시 다시 시작하도록 서비스를 구성합니다.

Environment.Exit(1);

나는 내 서비스에서 같은 일을했습니다. 잘 작동합니다.

참고 URL : https://stackoverflow.com/questions/1454502/how-can-i-restart-a-windows-service-programmatically-in-net

반응형