问题描述
我正在使用 WMI 在远程机器上停止服务:
i'm stoppinga service on remote machine with WMI:
protected override void Execute()
{
ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = RemoteMachineUsername;
connectoptions.Password = RemoteMachinePassword;
ManagementScope scope = new ManagementScope(@"\\" + RemoteMachineName + @"\root\cimv2");
scope.Options = connectoptions;
SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + ServiceName + "'");
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject service in collection)
{
if (service.GetPropertyValue("State").ToString().ToLower().Equals("running"))
{
//Stop the service
service.InvokeMethod("StopService", null);//HOW TO WAIT FOR THIS TO FINISH?
}
}
}
}
现在,这个方法在服务停止之前很久就完成了.我的问题是,我如何等待服务停止以及如何知道它是否成功.换句话说,我想以同步的方式做到这一点.
now, this method finished long before the service is stopped. my question is, how can i wait for the service to be stopped and how can i know if it succeeded. in other words, i want to do this in a sync way.
谢谢!
推荐答案
StopService 返回一个 uint
状态代码,您可以将 InvokeMethod
的结果全部转换为 uint
并检查其返回值.
StopService returns a uint
status code you you can cast the result of your InvokeMethod
all to an uint
and check its return value.
调用应该是同步的,但如果服务没有立即响应停止请求,它可能会超时.如果是这种情况,您可以始终循环检查服务 State
属性.
The call already should be synchronous, but it could be timing out if the service doesn't respond to the stop request immediately. If that is the case you could always loop on checking the service State
property.
这篇关于等待 service.InvokeMethod 完成 - WMI、C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!