C#Windows服务自我终止服务 [英] C# Windows service self terminate service
问题描述
您如何使服务自我终止?
How do you have a service self terminate?
环境.退出将导致应用启动,但服务保持运行状态.
Environment.Exit will cause the app to start but the service stays running.
有什么主意吗?
推荐答案
您可以使用SCM从服务本身内部关闭服务:
You can use the SCM to shut down your service from within the service itself:
System.ServiceProcess.ServiceController svc = new System.ServiceProcess.ServiceController("NameOfYourService");
svc.Stop();
另一个选择是调用 ServiceBase服务中的.Stop()
-如果您可以访问 ServiceBase
派生的类实例,这将是一种更干净的方法-在许多情况下,尽管这样做很麻烦传递这种依赖性.
The other option is to call ServiceBase.Stop()
in your service - if you have access to your ServiceBase
derived class instance that would be the cleaner way to go - in many cases it is cumbersome though having to pass this dependency around.
如果您有未捕获的异常,我个人将让服务崩溃(或先将其记录下来,然后 throw
),这将在事件日志中留下一条消息,详细说明终止原因.如果确实需要,可以捕获异常,然后调用 ServiceBase.Stop()
.
If you have an uncaught exception I personally would just let the service crash (or log it and then throw
), which will leave a message in the event log detailing the termination reason. If you absolutely need to you can catch the Exception, and then call ServiceBase.Stop()
.
这篇关于C#Windows服务自我终止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!