How to trigger failure in a windows service?

318 views Asked by At

For every windows service you can define "recover policy" indicating what to do in case of a failure.

This works for when the service fail to start, but how can I trigger "failure" if the service started successfully but did something wrong while running? I tried to throw exception but the service controller just hides it, I tried to set exit code to 1 and call Stop() but it just stops gracefully..

Is there a way to tell windows "this service has crashed and want to use the recovery policy" from code and after it had successfully started? If its not possible to trigger the recover policy after started that's OK, but whats the best way to stop while indicating windows there was an error?

Thanks,

1

There are 1 answers

0
Vedran On

As per MSDN documentation the correct way is to exit the service with a non-zero return code.

Environment.Exit(1);

If you have configured the recovery options for your service, in Windows System logs you will then see a message such as this one:

... service terminated unexpectedly. The following corrective action will be taken in 60000 miliseconds: Restart the service.