[点晴永久免费OA]C#获得服务,判断服务状态,启动服务
|
admin
2019年9月5日 21:23
本文热度 2594
|
获取服务
首先要添加引用: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);
}
启动服务
var server = serviceControllers.FirstOrDefault(service => service.ServiceName == serviceName);
if (server!=null && server.Status != ServiceControllerStatus.Running)
{
server.Start();
}
开一个线程定期检测服务状态
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();
}
}
该文章在 2019/9/5 21:23:37 编辑过