17

I'm trying to understand the difference between OnStart() and the constructor in a ServiceBase derived class. From reading around it seems that the first time you start a service (after turning on your machine), the constructor is called. Thereafter, you can stop and start the service as many times as you like, but the constructor will never be called again, only the OnStart() method will be called each time. Can anyone confirm?

Thanks

2
  • Yes, I can confirm that. And it's entirely logical. Commented May 13, 2011 at 19:53
  • Thank you for asking this question.
    – alvonellos
    Commented Jul 3, 2014 at 15:51

3 Answers 3

17

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called. MSDN

3
  • Thanks. Just wanted to confirm I understood. Studying for my 70-536.
    – Ronnie
    Commented May 13, 2011 at 21:37
  • 2
    So if I have a service and need to, for example, initialize an event handler, I would want to do that in the onStart? Or no because it would initialize multiple instances on the handler? Commented Oct 21, 2011 at 19:54
  • if you subscribe to the event on the OnStart you should unsubcribe to the event in the OnStop.
    – johnw182
    Commented Jul 7, 2014 at 19:32
5

A slight variant is that it does depends on if it contains one service or multiple services. Here's the line from the docs

If the executable contains a single service, the system calls the service's constructor when Start is selected from the SCM, and runs the destructor if Stop is called.

If the executable contains multiple services, calling Start on one service causes the constructors to be called for all services in the executable, but only the specified service is started. Destructors for the services are run together when all services have been stopped, not individually when each service is stopped.

But oxilumin's answer probably is what you're after.

1
  • I think it should be the right answer
    – Rougher
    Commented Apr 18, 2022 at 13:03
2

Yes this is correct. The constructor is called once per load and the on start can happen when a user (or automation) starts and stops the service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.