如何在.NET中以编程方式重新启动Windows服务

Nem*_*emo 64 c# windows-services

如何在.NET中以编程方式重新启动Windows服务?
此外,我需要在服务重启完成后执行操作.

Don*_*nut 70

本文使用ServiceController该类编写启动,停止和重新启动Windows服务的方法; 可能值得一看.

文章中的片段("重新启动服务"方法):

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
  {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Slavik如果需要管理员权限,那么您以编程方式采取什么方法并不重要;您可能甚至需要使用管理级控制台来使用命令行工具,如果您通过任务管理器尝试,则可能会被拒绝访问。 (4认同)

Fre*_*els 36

看一下ServiceController类.

要执行重新启动服务时需要执行的操作,我想您应该自己在服务中执行此操作(如果它是您自己的服务).
如果您无法访问服务的来源,那么也许您可以使用该WaitForStatus方法ServiceController.

  • 这在服务本身内有效吗?Windows 服务可以通过编程方式自行重启吗? (2认同)

小智 22

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Dru*_*uid 16

您也可以调用该net命令来执行此操作.例:

System.Diagnostics.Process.Start("net", "stop IISAdmin");
System.Diagnostics.Process.Start("net", "start IISAdmin");
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案,因为它不需要额外的引用或帮助类。你可能想添加一个 .WaitForExit(); 在再次启动之前确保服务已停止:`System.Diagnostics.Process.Start("net", "stop IISAdmin").WaitForExit();` System.Diagnostics.Process.Start("net" , "启动 IISAdmin").WaitForExit();` (4认同)

Hak*_*tık 8

这个答案是基于@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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*lan 6

怎么样

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

theController.Stop();
theController.Start();
Run Code Online (Sandbox Code Playgroud)

不要忘记将System.ServiceProcess.dll添加到项目中以使其工作.