Şafak Gür
Şafak Gür

Reputation: 7355

Should I call base class' methods in Windows services?

When deriving from ServiceBase, should I call the methods of the base class, too?

protected override void OnStart(string[] args)
{
    //
    // The stuff I do when the service starts.
    //

    base.OnStart(args); // Do I need to call this?
}

Upvotes: 14

Views: 2334

Answers (3)

TGlatzer
TGlatzer

Reputation: 6258

If you decompile the service base with ILSpy or similar, you will see, that OnStart, OnStop, etc. do nothing (at least in .NET 4.0/4.5).

But this behaviour could change some time, so there could be unwanted or unpredicted behaviour in future releases of .NET, if you do not call it.
I think it's a good practice to call those base.OnEvent()-Methods.

Upvotes: 5

Tim Copenhaver
Tim Copenhaver

Reputation: 3302

The short answer is yes, you should.

In this specific case, the base implementation of the OnStart method doesn't do anything significant, but that is an implementation detail which could change at any time. As a general practice, you should always call the base method unless you have a good reason not to.

Upvotes: 17

KennyZ
KennyZ

Reputation: 907

I don't think I ever called base.OnStart when I wrote services.

If you do, however, always make the base class call the first line of your method, not the last!

Upvotes: 0

Related Questions