It is not an easy job to write a windows service in unmanaged. There are many guidelines you need to follow to make the service work. Programming Server-Side Applications for Microsoft Windows 2000 is good reference to learn how to write a windows service.

 

It is much easier to writing a service in managed code using System.ServiceProcess.ServiceBase and related classes. However I think it is still important to understand how to write an unmanaged service before you start writing a managed service.

 

When SCM (Service Control Manager) spawns a service executable to call StartServiceCtrlDispatcher, if StartServiceCtrlDispatcher is not called within 30 seconds, the SCM think that the service executable is malfunctioning and calls TerminateProcess to kill the process. In managed services. StartServiceCtrlDispatcher is called in ServiceBase.Run. Normally ServiceBase.Run is called from Main. We have seen reports about timeout in managed service startup. Most of the time, it is because of some expensive operations happened before Main is executed.

 

Following is an example:

public class TestService: System.ServiceProcess.ServiceBase {

   

private static System.Diagnostics.PerformanceCounter lbTimer = null;

static TestService () {

lbTimer = new System.Diagnostics.PerformanceCounter("TestService", " Frequency");

}

 

static void Main() {

System.ServiceProcess.ServiceBase[] ServicesToRun;

ServicesToRun = new System.ServiceProcess.ServiceBase[] { new PhoIIS() };

System.ServiceProcess.ServiceBase.Run(ServicesToRun);

}

       

}

 

Note the static constructor is executed before Main. Creating a performance counter could be expensive. So this can cause the Service to timeout during startup. The fix is to do the initialization in a separate thread.