C# Windows Service Main Method

cnetwindows-services

I'm curious how exactly the Main() method works in a windows service as it relates to the Service Control Manager. When is it executed? How does it hook into the OS? Is it executed when a service is installed? I know it is executed when OnStart() is called by the SCM, OnStop() it's already running so we wouldn't execute it again.

If anyone knows a lot about this area and can elaborate I would appreciate it.

I am an expeirenced programmer, I don't need a description of what the Main Method does in general…just how it works in conjunction with windows services.

Best Answer

When you use the Control Panel applet to tell the service to start the SCM launches the process; this causes the code inside of Main() to run. The ServiceBase.Run() line in the Main() method hooks the associated services into the SCM who then calls the OnStart() method for each of the services specified in the ServiceBase.Run() method call.