Search code examples
c#windows-servicesstatus

Setting Windows Service's Status


I'm trying to create a windows service that runs an exe that I have. I have been using this guide from msdn.

I run my exe as a Process that is started in OnStart and stopped in OnStop. I want to know how the service status, the status sc query *name*, is updated.

I've tried following the status section, here, of the guide above, but calling

serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);

and those type of functions from the guide don't seem to do anything.

I want to be able to set the status of the service to be stopped, if my exe that the service runs crashes or is killed.

One idea I have in mind is to have a separate function that is run in a thread from OnStart that will block using process.WaitForExit();. And after thread stops blocking, I wanted to use the functions above to set the service status as stopped.

Does anyone have any idea on why I can't set the service status, or how to link the service status to the exe that the service runs? Thanks


Solution

  • Do not set the service status. It sounds like you should stop your service when the exe crashes or is killed. To stop the service, use ServiceBase.Stop()

    https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.stop.aspx

    This will change the service status to stopped.