• 这个例子展示了如何用C#编程实现启动、停止和重启Windows服务。


    这个例子展示了如何用C#编程实现启动、停止和重启Windows服务。

    启动服务

    下面的方法尝试通过指定的服务名称启动服务。然后等待知道服务运行或发生超时。

    [C#]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public static void StartService(string serviceName, int timeoutMilliseconds)
    {
      ServiceController service = new ServiceController(serviceName);
      try
      {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
     
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
      }
      catch
      {
        // ...
      }
    }
    停止服务
     
    下面的方法尝试停止指定的服务,然后等待服务停止或发生超时。
     
    [C#]
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public static void StopService(string serviceName, int timeoutMilliseconds)
    {
      ServiceController service = new ServiceController(serviceName);
      try
      {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
     
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
      }
      catch
      {
        // ...
      }
    }
    重启服务
    这个方法是上两个方法的合并,尝试停止服务(并等待,直到它停止)然后启动服务(直到服务运行)。指定的超时时间是两个操作合计的超时时间。
  • 相关阅读:
    Codeforces Round #217 (Div. 2)B. Berland Bingo
    走迷宫1 bnu 1054
    MFC 对话框背景图片
    用Visual C++从位图文件生成任意形状的窗口
    poj 2245 Lotto
    poj 1797 Heavy Transportation
    poj 2253 Frogger
    poj 1125 Stockbroker Grapevine
    B. Books
    【转】阻塞与非阻塞socket的优缺点
  • 原文地址:https://www.cnblogs.com/skyay/p/12109618.html
Copyright © 2020-2023  润新知