C#Windows服务 - 处理异常的启动异常、Windows

2023-09-03 01:52:07 作者:生活一半记忆一半继续

我写了一系列的Windows服务。我想,如果在启动过程中抛出错误(的OnStart()方法)他们失败。我原以为只是抛出一个错误,在的OnStart()将做到这一点,但我发现,而是开头和presents我一个消息,说明该服务已启动,但无效。这是正确的吗? (释义)。如何做到这一点,实际上无法启动服务,我处理错误?

I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?

推荐答案

如果您运行的是.NET 2.0或更高版本,可以使用的 ServiceBase.Stop 以阻止的OnStart服务。否则,从一个新的线程中调用停止。

if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.

文献[devnewsgroups](的http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)

(新闻集团走了)