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();
}
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();
}
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.
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.
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.
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.