Should a new thread be created in ServiceMain?

MSDN says that:

"The ServiceMain function should create a global event, call the RegisterWaitForSingleObject function on that event, and exit. This will terminate the thread that starts the ServiceMain function, but will not terminate the service ..."

So the question is, should a new thread be created inside the ServiceMain function to execute the service code, or can I just set the service to RUNNING state and use the ServiceMain thread to start the service code? If a ServiceMain thread is used to run a service code, the SCM will remain blocked even if the service state is set to RUNNING?

+3


source to share


2 answers


I don't think the way to implement the services described in this statement from MSDN is the only possible way. This would contradict the MSDN service example at http://msdn.microsoft.com/en-us/library/windows/desktop/bb540476(v=vs.85).aspx . In this example, the service is waiting for events on the same thread called ServiceMain. This method is probably best for simple services that work fine with a single thread.



If you choose to use the RegisterWaitForSingleObject method, you don't need to explicitly create streams. The MSDN page for RegisterWaitForSingleObject says "New wait threads are automatically created when needed." You need to open I / O pipes that the service will monitor and bind its handles to the thread pool before exiting ServiceMain.

+2


source


MSDN says : "The Service Control Manager (SCM) is waiting for the service to report a status SERVICE_RUNNING

. It is recommended that the service reports this status as soon as possible, as other components in the system that require interaction with the SCM will be blocked during this time. . "

The control manager creates a new thread to execute the ServiceMain function for this service. The ServiceMain function should perform the following tasks.

5. Perform service tasks or, if there are no pending tasks, return control to the caller. Any change to the terms of service is a call SetServiceStatus

to report new status information.



It follows from this that you can perform more complex initialization tasks inside the ServiceMain function, such as creating additional threads.

A guide for creating multithreaded services .

0


source







All Articles