Each service has a control handler, the Handler function, that is invoked by the control dispatcher when the service process receives a control request from a service control program. Therefore, this function executes in the context of the control dispatcher.
Whenever the Handler function is invoked, the service must call the SetServiceStatus function to report its status to the SCM. This must be done regardless of whether the status changed.
The service control program send control requests using the ControlService function. All services must accept and process the SERVICE_CONTROL_INTERROGATE control code. You can enable or disable acceptance of the other standard control codes by calling SetServiceStatus. Services can also handle additional user-defined control codes.
The control handler must return within 30 seconds, or the SCM will return an error. If a service needs to do lengthy processing when the service is executing the control handler, it should create a secondary thread to perform the lengthy processing, then return. This prevents the service from tying up the control dispatcher. For example, when handling the stop request for a service that will take a long time, create another thread to handle the stop process. The control handler should simply call SetServiceStatus with the SERVICE_STOP_PENDING message and return.
When the user shuts down the system, all control handlers receive the SERVICE_CONTROL_SHUTDOWN control code. They are notified in the order that they appear in the database of installed services. By default, a service has approximately 20 seconds to perform cleanup tasks before the system shuts down. However, if the system is left in the shutdown state (not restarted or powered down) the service continues to run. You can change the time the system will wait for service shutdown by modifying the WaitToKillServiceTimeout value in the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
For more information, see Writing a Control Handler Function.