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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With