C# Windows service self terminate service

血红的双手。 提交于 2019-12-19 07:32:04

问题


How do you have a service self terminate?

Environment.Exit will cause the app to start but the service stays running.

Any idea?


回答1:


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();

Edit:

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.

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().



来源:https://stackoverflow.com/questions/6892266/c-sharp-windows-service-self-terminate-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!