c# - ServiceController status 没有正确反射(reflect)实际的服务状态

标签 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();
    }

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

最佳答案

ServiceController.Status 属性并不总是有效;它在第一次被请求时被惰性评估,但是(除非被请求)那一次;随后对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(),如果它最初是Stopped(例如),它将总是Stopped

关于c# - ServiceController status 没有正确反射(reflect)实际的服务状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12192097/

相关文章:

C# 监听端口的服务

c - 如何正确使用SetServiceStatus告诉Windows我的服务正在停止?

c# - Windows 服务总是 "Starting"

c# - 无法访问 Azure 上发布的 Web api

c# - 如果使用 FieldOffset,则必须在每个类/结构成员上使用它吗?

C# Regex - 匹配不以特定单词开头的表达式

c# - 无法在 Windows XP Embedded 上启动以 .NET 2.0 编写的服务

.net - 异步调用与多线程

C# 将整数显示为二进制/十进制。怎么换显示器?

c# - 如何计算传输速率speed kb/s SOCKETS c#