Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# service - OnStart() v Constructor

Tags:

c#

.net

service

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

like image 817
Ronnie Avatar asked May 13 '11 19:05

Ronnie


2 Answers

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

like image 185
oxilumin Avatar answered Oct 05 '22 13:10

oxilumin


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.

like image 5
Conrad Frix Avatar answered Oct 05 '22 12:10

Conrad Frix