最近在编写一个对Winodows 服务的监控,需要定时重起服务,然后发现System.ServiceProcess简单又好用,方法如下,
using System.ServiceProcess;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/// <summary> /// 重起服务 /// </summary> /// <param name="ServicesName">服务名</param> public static void RestartServices(string ServicesName) { ServiceController service = new ServiceController(ServicesName); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } |
//—例如我重起文件共享的服务”Server”
RestartServices(“Server”);