獲取服務(wù)
首先要添加引用:System.ServiceProcess
然后導(dǎo)入命名空間:using System.ServiceProcess;
var serviceControllers = ServiceController.GetServices();
foreach (var service in serviceControllers)
{
Console.WriteLine("ServiceName:{0}\t\tServiceStatus:{1}", service.ServiceName, service.Status);
}
啟動(dòng)服務(wù)
var server = serviceControllers.FirstOrDefault(service => service.ServiceName == serviceName);
if (server!=null && server.Status != ServiceControllerStatus.Running)
{
server.Start();
}
開一個(gè)線程定期檢測服務(wù)狀態(tài)
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 編輯過