简体   繁体   中英

Can a service written in .NET self-terminate?

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.

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?

尝试ServiceBase.Stop()

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

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.

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

EDIT: I suspect this answer is the best one really, but I'll leave this up (for the moment) just for the sake of interest.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM