What is the proper way for a Windows service to fail during its startup

我们两清 提交于 2019-12-10 22:44:48

问题


I need my service to check for existence and structure of certain files during its startup and exit/fail/stop if some conditions aren't met. I read this thread: What is the proper way for a Windows service to fail? but it does not help.

I set the ServiceBase.ExitCode property non-zero and then call ServiceBase.Stop. But I get 5 event log entries. See below:

Starting service. (I log this event via code)
Config.xml file not found. (I log this ERROR event via code)
Service stopped successfully. (SCM logs this message)
Service started successfully. (SCM logs this message)
Service cannot be started. The handle is invalid  (SCM logs this message)

As you see everything goes OK except for the last two entries. Why are they there? What can I do to properly shutdown the service during startup? Why doesn't SCM see the service as stopped/failed?


回答1:


You don't provide enough code to really know, but I suspect you are trying to validate the service and stop it in either the constructor or the OnStart. The way I like to handle services is start my timer in the OnStart. In the first interval of the timer I can validate all the code, if its invalid close the Service. If its valid, reset the interval of the timer to how frequently I want it to run then set a bool that tells it not to check for validity of files again.




回答2:


What is the return code you are using for your ExitCode? If it matches the corresponding windows ExitCode, then that is what will be recorded by SCM. I'm assuming you are returning a 6 for your ExitCode.

The other thing is if you can run on Default values do that, let Config.xml be missing and just record the problem in the EventLog. "Configuration file Missing"

If you really want it to just abort during OnStart, set your ExitCode and then Throw an Exception (InvalidArgumentException, InvalidOperationException) for example

This article also has some good advice. .NET: Which Exception to Throw When a Required Configuration Setting is Missing?




回答3:


You are trying to start second instance of service (another service registered for the same .exe)



来源:https://stackoverflow.com/questions/15950553/what-is-the-proper-way-for-a-windows-service-to-fail-during-its-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!