Link to home
Start Free TrialLog in
Avatar of FroggedUp
FroggedUp

asked on

Forcing GUI to wait on ServiceController.WaitForStatus

Hey Folks,

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();

 try
            {

               
                if (svcStatus == "Running")
                {
                    myService.Stop();
                    myService.Refresh();
                    myService.WaitForStatus(ServiceControllerStatus.Stopped);
                }
               
                //once service is stopped, start it.
                if (svcStatus == "Stopped")
                {
                    myService.Start();
                    myService.Refresh();
                    myService.WaitForStatus(ServiceControllerStatus.Running);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.Source + "\n\n" + ex.InnerException);

            }
ASKER CERTIFIED SOLUTION
Avatar of Dennis Aries
Dennis Aries
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of FroggedUp
FroggedUp

ASKER

Duh, that was really stupid of me. without setting the status to the variable after each run, of course the start() call wouldn't fire. Whoops. Thanks guy!
This is not right. I pointed out the issue and my comment should be solution than assisted solution.