Forcing GUI to wait on ServiceController.WaitForStatus
Posted on 2014-03-04
I have a windows app written in C# with the express purpose of restarting services prior to launch of another custom application, and I'm trying to get the GUI to pause until the service is fully stopped before firing the start method, but the GUI doesn't seem to halt on servicecontroller.waitforstatus();
Everything works, but once the service is stopped, the code immediately advances and skips the second if clause because the service hasn't fully been stopped as of yet, so the start() method never fires. I could build an artificial delay with a wait or a pause, but I'd prefer to do it properly and figure out the waitforstatus option. Any thoughts greatly appreciated.
My code looks like this:
ServiceController myService = new ServiceController(serviceName);
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
string svcStatus = myService.Status.ToString();
if (svcStatus == "Running")
//once service is stopped, start it.
if (svcStatus == "Stopped")
catch (Exception ex)
MessageBox.Show(ex.Message + "\n\n" + ex.Source + "\n\n" + ex.InnerException);