Why call base.OnStop() when Windows Service is stopped?

二次信任 提交于 2019-12-19 05:20:37

问题


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:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3620170/why-call-base-onstop-when-windows-service-is-stopped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!