I'm writing an app to programmatically start/stop a Windows Service using ServiceController. I have a UI class that has some UI bells and whistles, and a Helper class that starts and stops the service.
In the Helper class:
void StopService()
{
var controller = new ServiceController("MyService");
if (controller.Status == ServiceControllerStatus.Running)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
}
}
In the UI class:
Helper.StopService();
var controller = new ServiceController("MyService");
if (controller.Status == ServiceControllerStatus.Stopped)
{
// Do some stuff
}
else
{
// MyService not stopped. Explode!
}
The problem is that when the service is stopping, the method in Helper immediately returns to the caller in UI class, without waiting the service to reach stopped (the service is eventually stopped after about 5-10 seconds). If I move the start/stop logic to the UI class, things got normal.
What silly mistake am I making here?