all groups > c# > october 2007 >
You're in the

c#

group:

Windows Service Question


Windows Service Question Smithers
10/1/2007 8:21:53 PM
c#: I'm writing a new Windows Service. During the OnStart event procedure I
initialize a few things. If initialization fails, then I do not want for the
service to start.

What I currently have is something like this:
if (All initialization tasks succeeded)
{
// log the fact that initialization succeded
// do some other stuff
}
else
{
// log the fact that initialization failed
this.Stop();
}


I'm not sure about my use of "this.Stop()" above. Does it even make sense to
put that in the OnStart event procedure...? has the service actually started
at this point? Is there a better way to accomplish the objective of "not
starting" the service when initialization tasks fail during the OnStart
event procedure?

Thanks!

Re: Windows Service Question Willy Denoyette [MVP]
10/2/2007 12:00:00 AM
[quoted text, click to view]


No it makes no sense to call "this.Stop":
1) the service did not report back to the SCM that it was started.
2) It never makes sense to call ServiceBase.Stop from within a service, this
method is meant to be called by the SCM.

All you can do here is throw an exception, the SCM will handle this as a
"failed to start " event and report it with an error message in the
application log.

Willy.
Re: Windows Service Question Laura T.
10/2/2007 12:00:00 AM

"Smithers" <A@B.com> ha scritto nel messaggio
news:%23aR1gNKBIHA.3716@TK2MSFTNGP03.phx.gbl...
[quoted text, click to view]
The SCM asks you to start the service process, by calling the OnStart
routine.
Before calling your OnStart(), the ServiceBase sets the service status to
pending so you don't have to.
If you fail to start/initialize, of course first you must you must cleanup
any resources you have, and then throw an exception from the OnStart(). The
exception is caught by the ServiceBase object that then sets the service
status as stopped and writes the exception string to the event log for
diagnostics, so it's a good idea to write detailed reason for the failure in
the exception.
Without exception, like a normal return;, would mark the process as started
and SCM would list it as started, even that it is not.

Using Stop(), would first override the SCM status to not started, but then
if you do a clean exit from the OnStart(), the ServiceBase would still mark
the service as running.


http://msdn2.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx
http://msdn2.microsoft.com/en-us/library/ms687414.aspx



[quoted text, click to view]
Re: Windows Service Question Smithers
10/2/2007 7:41:10 AM
Thanks Laura and Willy. Something just seemed wrong with having this.Stop()
in the OnStart event procedure... Now I know...

-S


[quoted text, click to view]

AddThis Social Bookmark Button