我需要我的服务在启动期间检查某些文件的存在和结构,如果不满足某些条件则退出/失败/停止。 我读了这个帖子:What is the proper way for a Windows service to fail? 但这没有帮助。
我将 ServiceBase.ExitCode 属性设置为非零,然后调用 ServiceBase.Stop。但我得到 5 个事件日志条目。见下文:
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 看不到服务已停止/失败?
最佳答案
您没有提供足够的代码来真正了解,但我怀疑您正在尝试验证服务并在构造函数或 OnStart 中停止它。我喜欢处理服务的方式是在 OnStart 中启动我的计时器。在计时器的第一个间隔内,我可以验证所有代码,如果它无效关闭服务。如果它有效,将计时器的间隔重置为我希望它运行的频率,然后设置一个 bool 值,告诉它不再检查文件的有效性。
关于c# - Windows 服务在启动期间失败的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950553/