views:

63

answers:

4

I'm creating a C#.Net Windows Service and am wondering if you always have to call base.OnStop(); in the service's OnStop() method and why?

protected override void OnStop()
{
    threadRunning = false;

    this.ExitCode = 0;
    base.OnStop();
}
+1  A: 

You don't have to. It just means that if you ever insert an extra base class between ServiceBase and your actual service, you'll call the OnStop method of that, if it's overridden. I don't believe ServiceBase.OnStop itself performs any actions.

Usually it's a good idea to call the base method when you're overriding IMO, unless you specifically want to prevent the "normal" behaviour from occurring... but in this case, omitting the call won't have any ill effects.

Jon Skeet
+2  A: 

You do not need to.

OnStop is a virtual method defined in ServiceBase to allow you an override where you can handle stopping of the service. In the (somewhat) general case, when you override a virtual method, you call the base virtual method as well. The only time you don't call it is when you want to stop the normal things from happening.

In the case of Servicebase, OnStop does nothing so you do not need to call it.

Philip Rieck
+3  A: 

From the documentation on ServiceBase.OnStop:

OnStop is expected to be overridden in the derived class. For the service to be useful, OnStart and OnStop should both be implemented in your service class.

So it's really used as a notification to your service that it is stopping.

A glance at the .NET source code for ServiceBase.cs reveals the method does nothing:

protected virtual void OnStop()
{
}

So, do you need to call it? No. But it is still good form to do so. The base implementation may change someday.

Paul Williams
The "good to call it" thing is a silly idea. If the base implementation did ever change - when do you call it? Before or after your own code? Too many unknowns to know whether to call or not, you're left entirely up to the documentation to fill in the gaps - so unless the doc tells you to call it, I wouldn't bother. IMO - the ability to call the base method is a silly idea and the language would be nicer without it. :p
Mark H
This is the implicit cost of inheritance, only good documentation can ever resolve this question. The ServiceBase class is teetering on the edge of having to have been designed as an abstract class. With OnStart and OnStop being abstract so there wouldn't be any guessing.
Hans Passant
+1  A: 

You actually don't have to make that call. If you look at the OnStop method in the ServiceBase class using Reflector, you will see that it does nothing at all.

qstarin