C# ServiceController状态不能正确反映实际的服务状态

C# ServiceController状态不能正确反映实际的服务状态,c#,windows-services,C#,Windows Services,如果我的服务正在启动或停止,则此代码将运行powershell脚本 Timer timer1 = new Timer(); ServiceController sc = new ServiceController("MyService"); protected override void OnStart(string[] args) { timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime);

如果我的服务正在启动或停止,则此代码将运行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();
    }
当我从cmd提示符终止服务时,它工作正常 但即使我的服务已启动并正在运行,powershell脚本仍会继续执行自身(它会在计算机上附加一个文件)
知道为什么吗?

ServiceController.Status属性并不总是活动的;它在第一次被请求时被延迟评估,但(除非被请求)仅在该时间进行评估;对
状态的后续查询通常不会检查实际服务。要强制执行此操作,请添加:

sc.Refresh();
在您的
.Status
检查之前:

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

如果没有
sc.Refresh()
,如果它最初被
停止
(例如),它将始终说
停止

,说powershell与此问题正交是否正确,真正的问题是:为什么我的
StartPending
/
Stopped
检查无法正常工作?您是否尝试过设置断点以查看到底发生了什么?啊!说真的,微软?为什么不在
状态
调用本身中构建一个刷新(就像我可能自己做的那样)??或者至少有一个
状态。刷新
方法使其变得明显。哇,伙计@马克,你让我开心。很难理解,我们必须调用sc.Refresh()来确定最新状态。