获取服务
首先要添加引用:System.ServiceProcess
然后导入命名空间:using System.ServiceProcess;
//获得服务集合
var serviceControllers = ServiceController.GetServices();
//遍历服务集合,打印服务名和服务状态
foreach (var service in serviceControllers)
{
Console.WriteLine(“ServiceName:{0}\t\tServiceStatus:{1}”, service.ServiceName, service.Status);
}
1
2
3
4
5
6
7
启动服务
//获取指定服务,若服务状态不是Runing就Start该服务
var server = serviceControllers.FirstOrDefault(service => service.ServiceName == serviceName);
if (server!=null && server.Status != ServiceControllerStatus.Running)
{
server.Start();
}
1
2
3
4
5
6
开一个线程定期检测服务状态
static void Main()
{
ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(true), new WaitOrTimerCallback(TryStartRServer3), null, 30000, false);
}
private static void TryStartRServer3(object state, bool timedout)
{
var serviceControllers = ServiceController.GetServices();
var server = serviceControllers.FirstOrDefault(service => service.ServiceName == “RServer3”);
if (server != null && server.Status != ServiceControllerStatus.Running)
{
server.Start();
}
}
————————————————
版权声明:本文为CSDN博主「I-Awakening」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/da_keng/article/details/50384914