Custom Service stop

Darryl Hoar 141 Reputation points
2022-10-21T20:47:30.553+00:00

I am using visual studio professional 2019 and c#.
I have created a service project, using the template in visual studio.

When this service starts, it validates several things. What I need to do is
abort the OnStart if certain validations fail. For instance, if the Com port specified
in the app.config file is invalid.

How do I do this? I can't call OnStop from within OnStart, so....

Any help greatly appreciated.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,223 questions
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2022-10-21T21:52:24.353+00:00

    You could just throw an exception in the OnStart method and that will cause the service not to start.

    If you want the app to report failures then you can open your service in design view & in the properties panel set the AutoLog property to true, then thrown exceptions will end up in your Windows Event Log:
    https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.autolog?view=dotnet-plat-ext-7.0

    0 comments No comments