C# System.ServiceProcess类操作Windows服务,判断服务状态,启动停止服务
获取服务
首先要添加引用: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);
}
启动服务
//获取指定服务,若服务状态不是Runing就Start该服务
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();
}
}
CSCODE.NET开发框架文库 - C/S框架网专注.NET技术、C/S架构快速开发框架软件
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
newdoc C/S框架网