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