Can a service written in .NET self-terminate?

前端 未结 4 1205
耶瑟儿~
耶瑟儿~ 2020-12-03 07:04

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

相关标签:
4条回答
  • 2020-12-03 07:41

    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.

    0 讨论(0)
  • 2020-12-03 07:41

    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.

    0 讨论(0)
  • 2020-12-03 08:00

    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.

    0 讨论(0)
  • 2020-12-03 08:03

    Try ServiceBase.Stop().

    0 讨论(0)
提交回复
热议问题