C # ExecuteCommand vs. Stopped Windows Service

I am developing an application to run in the background through a windows service. I created the service thanks to the MSDN tutorial and then I can start or stop it correctly.

My service needs to execute custom commands as well. Therefore, I applied the OnCustomCommand method in the service class.

I can send custom execution commands with command IDs from 128 to 255, which is everything I found on the net.

My problem: I cannot execute a command on the service when it stopped. ExecuteCommand()

throws a System.InvalidOperationException

every time I call it on serviceController

.

Cannot control <myservice> service on computer '.'

      

This does not happen when the service is running.

MSDN says

When you call ExecuteCommand, the service status does not change. If the service was started, the status remains Running. If the service has been stopped, the status remains stopped, etc.

So, I suppose this is actually possible for the executeCommand

services that have stopped.

My service is installed as a LocalSystem service and serviceController

started with administrator rights.

Does anyone know how to solve this?

+1


a source to share


2 answers


Failed to execute ExecuteCommand on stopped service. I believe the documentation you are reading tells you that calling ExecuteCommand does not start the service if it is stopped. It doesn't say that you can still call the method; there is essentially no object to execute the on method. I think your best solution is to find a way to determine if the service is stopped, if any, restart it, and then call ExecuteCommand. Otherwise, you can use a dirty hack and try to make the call if it fails, catch the exception and start the service and try a second time. Not preferable, but possible.

EDIT:



Assuming you are using a ServiceController , you can use Status to determine if the service is running.

+3


a source


Unable to execute ExecuteCommands on a stopped service.



If it doesn't work, then it's not "there" to listen to the commands you send.

0


a source







All Articles