Ronnie
Ronnie

Reputation: 1079

C# service - OnStart() v Constructor

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

Upvotes: 17

Views: 8650

Answers (3)

Conrad Frix
Conrad Frix

Reputation: 52665

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.

Upvotes: 5

Hogan
Hogan

Reputation: 70531

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.

Upvotes: 2

oxilumin
oxilumin

Reputation: 4833

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

Upvotes: 17

Related Questions