ServiceController状态未正确反映实际服务状态

Hen*_*yer 14 c# windows-services

如果我的服务启动或停止,我有这个代码运行PowerShell脚本.

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();
    }
Run Code Online (Sandbox Code Playgroud)

当我从cmd提示符中删除我的服务时工作正常但是即使我的服务启动并运行,powershell脚本也会继续自行执行(它在计算机上附加一个文件)任何想法为什么?

Mar*_*ell 36

ServiceController.Status物业并非总是存在 ; 它在第一次被要求时被懒惰地评估,但是(除非要求)只是那个时间; 后续查询通常Status 不会检查实际服务.要强制这样做,请添加:

sc.Refresh();
Run Code Online (Sandbox Code Playgroud)

在你.Status检查之前:

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

没有它sc.Refresh(),如果它Stopped(例如)最初,它将永远Stopped.