当另一个Windows服务重新启动时,Windows服务如何以编程方式重新启动自身?

时间:2013-05-16 08:04:31

标签: c# windows-services

我在Windows服务项目上工作,我想在重新启动Lync Front-End service时重新启动我的Windows服务

我知道如何重新启动我的Windows服务我使用此answer,但我不知道如何在重新启动前端服务时重新启动它

我知道我可以使用ServiceController Class

检查Windows服务状态

2 个答案:

答案 0 :(得分:0)

在您的服务中运行此代码:

  EventLog log = EventLog.GetEventLogs().First(o => o.Log == "Security");
  log.EnableRaisingEvents = true;          
  log.EntryWritten += (s, e) => {p.print(e); };

为事件日志编写方法

  void test(EntryWrittenEventArgs entry)
     {
          //you can check event log in the log viewer and set 
           //EventLogEntryType   and InstanceId accordingly. 

            EventLogEntry evntLog=entry.Entry;
            if (evntLog.EntryType == EventLogEntryType.SuccessAudit && 
                evntLog.InstanceId==123)
            {

             //Code to restart the service
            }
       }

答案 1 :(得分:0)

I)Topshelf是一个用于轻松开发Windows服务的开源项目。它会节省您的时间,即使您决定不使用它,您也可以从它的源代码中学习。

II)简短的回答是你必须轮询其他服务的状态。没有(普通)基于事件的机制。

如果您无法对其他服务进行任何修改,那么您可以通过(在单独的任务中)轮询其状态:

var sc = new ServiceController(serviceName);
status = sc.Status;

使用您提到的答案重启您的答案(并再次在OnStart中进行轮询,直到其他服务完全开始)。

但是如果你可以修改其他服务,那么你可以使用管道或命名互斥的其他方法来做到这一点(再次需要在单独的任务或OnStart和OnStop中进行轮询)。

相关问题