c# – WaitForExit用于远程计算机上的进程

我正在使用WMI to start a process on a remote machine.创建进程的调用立即返回,我也获得了远程机器上进程的id.

我想等待远程进程完成.一种选择是轮询具有给定id的远程机器上的进程是否仍然存在.

但是,我想知道是否有更好的方法来实现这一点,可能使用本机WinAPI函数?

仅用于获取更多信息,这是我目前用于启动远程进程的代码:

ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;

connOptions.Username = domainUserName;
connOptions.Password = password;

ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", host), connOptions);
manScope.Connect();

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = commandLine;

ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
最佳答案
我不知道这有多有效,你可以使用ManagementEventWatcher来查看查询.

这是我在网上找到的东西.

WqlEventQuery wQuery = 
 new WqlEventQuery("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'");

using (ManagementEventWatcher wWatcher = new ManagementEventWatcher(scope, wQuery))
{    
  bool stopped = false;

  while (stopped == false)
  {
    using (ManagementBaseObject MBOobj = wWatcher.WaitForNextEvent())
    {
      if (((ManagementBaseObject)MBOobj["TargetInstance"])["ProcessID"].ToString() == ProcID)
      {
        // the process has stopped
        stopped = true;
      }
    }
  }

  wWatcher.Stop();
}

转载注明原文:c# – WaitForExit用于远程计算机上的进程 - 代码日志