views:

678

answers:

3

I'm writing a windows service in .net 2.0.

What should I do within the OnStart method if for some reason I don't want it to start? Can I simply call the Stop() method of the base class (ServiceBase)? I've tried that and am getting some funny memory access exceptions. Is it required to start a separate thread to call the Stop() method?

+5  A: 

Why do you want to do that? If there's an error, log it in event log and throw an exception. Your service won't be started and the user will be informed that something bad happened.

Mehrdad Afshari
Indeed, if you throw an exception, the service won't get started. Windows Services handles this all for you.
Noldorin
There's lots of reasons why one might not want a service to start! So perhaps you're not really asking why, but rather suggesting the answer is to throw an exception? How about setting ServiceBase.ExitCode - is that advisable/necessary?
Rory
@Rory: Failing to start a service is a different thing from starting and stopping immediately. I'm against starting successfully and quietly stopping. ExitCode will be logged in the event log so you might want to consider setting it. It's not required though.
Mehrdad Afshari
Actually I think if you throw an exception, it *does* start, and then stops straight away. At least thats the message I get in services.msc. I believe you have to set ExitCode to make it not start at all...
Nathan Reed
A: 

Use a ServiceController and stop it via that then immediately return.

Lloyd
A: 

You could use Environment.FailFast(). Just be aware that it ignores any try-catch-finally blocks.

AJ