C# 用 .NET 编写的服务可以自终止吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a service written in .NET self-terminate?
提问by Chris Miller
I have a service application written in C# and under certain circumstances, I would like it to terminate itself. This would happen after the service has been running for a while, so this would not be happening in the OnStart() event.
我有一个用 C# 编写的服务应用程序,在某些情况下,我希望它自行终止。这会在服务运行一段时间后发生,因此在 OnStart() 事件中不会发生这种情况。
Everything that I have read so far suggests that the only safe way to terminate a service is through the Service Control Manager. My service runs as Local Service and does not have the rights to start or stop services, so I can't access the SCM from the service itself. Is there another way to self-terminate while still playing by the rules of the SCM?
到目前为止,我所读到的所有内容都表明,终止服务的唯一安全方法是通过服务控制管理器。我的服务作为本地服务运行,无权启动或停止服务,因此我无法从服务本身访问 SCM。是否有另一种方法可以在仍然遵守 SCM 规则的同时自行终止?
采纳答案by configurator
回答by Jon Skeet
What happens if you just let all the executing threads finish? I can imagine three possible outcomes:
如果你只是让所有正在执行的线程完成会发生什么?我可以想象三种可能的结果:
- The SCM notices, and decides you finished appropriately
- The SCM notices, thinks you died, and restarts you
- The SCM doesn't notice, and shows you as still running
- SCM 会注意到,并决定您是否正确完成
- SCM 注意到了,认为你死了,然后重启你
- SCM 没有注意到,并显示您仍在运行
EDIT: I suspect this answeris the best one really, but I'll leave this up (for the moment) just for the sake of interest.
回答by casperOne
Don't have the service run under Local Service. Have it run under a user that has the rights to stop a service.
不要在本地服务下运行该服务。让它在有权停止服务的用户下运行。
Although the idea of self-terminating services is not the best of ideas. That very fact alone means that it should be an application, and not a service.
虽然自我终止服务的想法并不是最好的想法。这个事实本身就意味着它应该是一个应用程序,而不是一个服务。
回答by Martin Liversage
If you want to terminate the service instead of stopping it (perhaps because the service has caught an otherwise unhandled exception) you can use Environment.Exit(1)
(use another exit code if you want).
如果您想终止服务而不是停止它(可能是因为服务捕获了未处理的异常),您可以使用Environment.Exit(1)
(如果需要,可以使用另一个退出代码)。
Windows will discover that the service has terminated unexpectedly. If the service has been configured to recover the recovery procedure will be used which includes options for restarting the service, running a program or restarting the computer.
Windows 会发现该服务意外终止。如果服务已配置为恢复,则将使用恢复过程,其中包括用于重新启动服务、运行程序或重新启动计算机的选项。