服务如何控制自己的状态?
时间:2020-03-06 14:51:22 来源:igfitidea点击:
我有一个继承自ServiceBase类的标准Windows服务器。
在OnStart方法上,我想先检查某些条件,然后再达到服务功能的主要目的。
例如:
protected override void OnStart(string[] args) { if (condition == false) { EventLog.WriteEntry("Pre-condition not met, service was unable to start"); // TODO: Convert service state to "Stopped" because my precondition wasn't met return; } InnitializeService(); }
任何人都可以很好地说明服务如何控制自己的状态?
解决方案
引发异常。这将导致服务MMC出错,并且异常消息和堆栈将自动记录到事件日志中。在这种情况下,我使用ApplicationException。
此外,该服务将返回到"未运行"状态。
如果以后需要停止,可以在ServiceBase上调用Stop方法。
在"计算机管理" MMC应用程序中向用户显示的错误似乎在Vista中无法正确获取异常文本。它显示以下内容:
The "your service name here" service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
但是,它可以正确地写入事件日志。
很酷。谢谢。