Restarting a service from within itself using ServiceController

S

sexauthor

I've written a windows service am unsure how we're meant to handle
fatal errors once the service is already up and running. It also
doesn't seem to be mentioned in any of the books or examples I've
seen.

Most example services, if they encounter an error, simply stop
processing but stay active.

The route I've taken to avoid that is, on catching a fatal exception,
I create a ServiceController instance and issue a Stop command. This
then shuts down the service properly.

On the other hand, I'd also like to be able to restart the service.
It stands to reason I can't issue a stop followed by testing the
status and then starting it again ... because of course my own process
can't finish stopping while I'm in it waiting :)

So, what are we meant to do?

(Unfortunately, in this circumstance, we're interfacing with an
unmanaged DLL that, when it has an error, doesn't come back properly
until you restart the process that has called it).
 
J

John Vottero

I've written a windows service am unsure how we're meant to handle
fatal errors once the service is already up and running. It also
doesn't seem to be mentioned in any of the books or examples I've
seen.

Most example services, if they encounter an error, simply stop
processing but stay active.

The route I've taken to avoid that is, on catching a fatal exception,
I create a ServiceController instance and issue a Stop command. This
then shuts down the service properly.

On the other hand, I'd also like to be able to restart the service.
It stands to reason I can't issue a stop followed by testing the
status and then starting it again ... because of course my own process
can't finish stopping while I'm in it waiting :)

So, what are we meant to do?

I recommend throwing (or rethrowing) a fatal exception. Then, the service
control manager will handle the exception and possibly restart the service
as specified in the "Recovery" tab of the service definition. Why reinvent
the wheel?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top