1.首先加入引用:

using System.ServiceProcess;

2.控制启动服务:

public void Start()
{
    var timeout = TimeSpan.FromSeconds(60);
    try
    {
        _serviceController.Start();
        _serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    catch (Exception ex)
    {
        throw new Exception("Service " + _serviceName + " is not started as expected, error: " + ex.Message);
    }
}  

3.控制停止服务:

public void Stop()
{
    var timeout = TimeSpan.FromSeconds(60);
    try
    {
        if (_serviceController.Status != ServiceControllerStatus.Stopped &&
            _serviceController.Status != ServiceControllerStatus.StopPending)
        {
            _serviceController.Stop();
            _serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Service " + _serviceName + " is not stoped as expected, error: " + ex.Message);
    }
}  

4.控制重启服务:

public void Restart()
{
    Stop();
    Start();
}  

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2021-07-20
  • 2021-08-29
猜你喜欢
  • 2022-12-23
  • 2022-01-02
  • 2022-02-17
  • 2021-12-21
  • 2022-12-23
  • 2022-01-30
  • 2022-12-23
相关资源
相似解决方案