System.ServiceProcess.ServiceController weirdness

M

Mark

Hi...

I inherited some code where someone wanted to start/stop services and
display a little ... progress bar while waiting.

Originally it was implemented with

ServiceController.{Start|Stop}()
for (int i = 0; i < 60; i++)
{
Console.WriteLine (".");
try
{
ServiceController.WaitForStatus (desiredState, TimeSpan.FromSeconds(1));
}
catch
{//ignore}
if (ServiceController.Status == desiredState) break;
}

Knowing how expensive exception processing is, I tried replacing it with
if (ServiceController.Status == desiredState) break;
Thread.Sleep(1000);

I'm finding, however, that the direct comparison is never reached no matter
how long I wait. Unless WaitForStatus is called (and the exception that
comes with it, usually 4 or 5 seconds/exceptions), the comparison doesn't
work.

I didn't find anything in the docs about this; is this just a known oddity
of the ServiceController? Seems like WaitForStatus could at least have been
friendlier and returned some kind of boolean success rather than throw an
exception - like WaitForMultipleObjects in the old days.

thanks
Mark
 
W

Walter Wang [MSFT]

Hi Mark,

If you use Reflector (http://www.aisto.com/roeder/dotnet/) to view the
ServiceController's implementation, you will see the WaitForStatus() is
also calling Refresh() while checking the status:

public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan
timeout)
{
if (!Enum.IsDefined(typeof(ServiceControllerStatus), desiredStatus))
{
throw new InvalidEnumArgumentException("desiredStatus", (int)
desiredStatus, typeof(ServiceControllerStatus));
}
DateTime utcNow = DateTime.UtcNow;
this.Refresh();
while (this.Status != desiredStatus)
{
if ((DateTime.UtcNow - utcNow) > timeout)
{
throw new TimeoutException(Res.GetString("Timeout"));
}
Thread.Sleep(250);
this.Refresh();
}
}


The Refresh() is a public method.

I understand your concern here is that the exception is expensive; however,
from the timing aspect of this issue, as we're already waiting using sleep,
this is actually might not be a very big issue.


Regards,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top