Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceController status does not correctly reflect the actual service status

I have this code running a powershell script if my service is starting or stopped.

Timer timer1 = new Timer();

ServiceController sc = new ServiceController("MyService");

protected override void OnStart(string[] args)
    {
        timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer1.Interval = 10000;
        timer1.Enabled = true;
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        if ((sc.Status == ServiceControllerStatus.StartPending) || (sc.Status ==  ServiceControllerStatus.Stopped))
        {
            StartPs();
        }
    }

    private void StartPs()
    {
        PSCommand cmd = new PSCommand();
        cmd.AddScript(@"C:\windows\security\dard\StSvc.ps1");
        PowerShell posh = PowerShell.Create();
        posh.Commands = cmd;
        posh.Invoke();
    }

It's working fine when I kill my service from cmd prompt But even if my service is up and running, the powershell script continues to execute itself (it appends a file on the computer) Any idea why ?

like image 930
Henry Meyer Avatar asked Aug 30 '12 07:08

Henry Meyer


1 Answers

The ServiceController.Status property is not always live; it is lazily evaluated the first time it is requested, but (unless requested) only that time; subsequent queries to Status will not normally check the actual service. To force this, add:

sc.Refresh();

before your .Status check:

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    sc.Refresh();
    if (sc.Status == ServiceControllerStatus.StartPending ||
        sc.Status == ServiceControllerStatus.Stopped)
    {
        StartPs();
    }
}

Without that sc.Refresh(), if it was Stopped (for example) initially, it will always say Stopped.

like image 100
Marc Gravell Avatar answered Oct 17 '22 06:10

Marc Gravell