Windows 服务在启动期间失败的正确方法是什么 [英] What is the proper way for a Windows service to fail during its startup

查看:41
本文介绍了Windows 服务在启动期间失败的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不满足某些条件,我需要我的服务在启动和退出/失败/停止期间检查某些文件的存在和结构.我读了这个线程:什么是正确的方法Windows 服务失败?但它没有帮助.

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.

我将 ServiceBase.ExitCode 属性设置为非零,然后调用 ServiceBase.Stop.但我得到 5 个事件日志条目.见下文:

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)

如您所见,除了最后两个条目外,一切正常.他们为什么在那里?如何在启动期间正确关闭服务?为什么 SCM 没有将服务视为停止/失败?

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?

推荐答案

您没有提供足够的代码来真正了解,但我怀疑您正在尝试验证服务并在构造函数或 OnStart 中停止它.我喜欢处理服​​务的方式是在 OnStart 中启动我的计时器.在计时器的第一个时间间隔内,我可以验证所有代码,如果无效则关闭服务.如果有效,将计时器的间隔重置为我希望它运行的频率,然后设置一个布尔值,告诉它不再检查文件的有效性.

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.

这篇关于Windows 服务在启动期间失败的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆