如果我的服务正在启动或停止,我会使用此代码运行 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/