简体   繁体   English

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

[英]How can a windows service programmatically restart itself when another windows service is restarted?

I work on windows service project , i want to restart my windows service when Lync Front-End service was restarted 我正在Windows服务项目上工作,我想在Lync Front-End service重新启动时重新启动Windows服务

i know how i restart my windows service i use this answer , but i don't know how i restart it when the Front-End Service was restarted 我知道我如何重新启动Windows服务,我使用此答案 ,但是当前端服务重新启动时,我不知道如何重新启动它。

and i know i can check the windows service status by use ServiceController Class 我知道我可以通过使用ServiceController类检查Windows服务状态

Run this code in your service : 在您的服务中运行以下代码:

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

Write a method for event log 编写事件日志的方法

  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
            }
       }

I) Topshelf is an open source project for developing Windows Services easily. I) Topshelf是一个易于开发Windows服务的开源项目。 It will save you time and even if you decide not to use it, you can learn from it's source code. 这样可以节省您的时间,即使您决定不使用它,也可以从其源代码中学习。

II) The short answer is you have to poll the status of the other service. II)简短的答案是您必须轮询其他服务的状态。 There is no (plain) event based mechanism for this. 没有基于(事件)事件的机制。

If you can not make any modifications to the other service then you can poll over it's status by (in a separate Task): 如果您不能对其他服务进行任何修改,则可以通过(在单独的任务中)轮询其状态:

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

And use the answer you've mentioned to restart yours (and again poll in OnStart until the other service get started completely). 并使用您提到的答案重新启动您的答案(并在OnStart中再次轮询,直到其他服务完全启动)。

But if you can modify the other service then you can use other means like pipes or named mutexes to do that (again needs polling in a separate Task or at OnStart and probably at OnStop). 但是,如果您可以修改其他服务,则可以使用其他方式(例如管道或命名的互斥体)来执行此操作(同样,需要在单独的Task或OnStart或OnStop上进行轮询)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM