none
How to stop a custom service from starting C# RRS feed

  • Question

  • Using VS 2015 Pro.  Have created a custom Windows service.   I check several conditions in the OnStart function.  If any of the conditions fail, I want the service to abort startup and quit.  How do I accomplish this ?

    Thanks.

    Monday, March 23, 2020 5:04 PM

All replies

  • You call SetServiceStatus with the current state set to SERVICE_STOPPED and a Win32 error code for the error log.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, March 23, 2020 5:51 PM
  • Hi ksukat63,

    Thank you for posting here.

    According to some information I found, in addition to Tim Roberts's method, setting ServiceBase.ExitCode to a non-zero value, and then calling ServiceBase.Stop seems to accomplish the same function, you can try it.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, March 24, 2020 9:31 AM
  • Hi,

    Has your issue been resolved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 9, 2020 7:54 AM
  • You can be blunt and call Environment.FailFast("Your reason goes here"). Once calling FailFast if there happens to be any clean up code or try-catch statements they will not be called.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, April 9, 2020 10:49 AM
    Moderator