.NET에서 원격 프로세스가 완료 될 때까지 기다립니다
-
21-08-2019 - |
문제
우리 모두는 알고 사랑하는 과정 .waitforexit ().
원격 시스템 (WMI/PSEXEC로 생성)의 프로세스 PID가 주어지면 어떻게 끝날 때까지 기다려야합니까?
해결책
Process.GetProcessById(processId, machineName).WaitForExit();
다른 팁
Me Process.getProcessByid ()가 작동하지 않았다 (기계에 연결할 수 없다고 주장 함). 이것은 효과가있었습니다 :
public static bool WaitForProcess(int pid, string machine, TimeSpan timeout)
{
// busy wait
DateTime start = DateTime.Now;
while (IsAlive(pid, machine))
{
if (start.Add(timeout).CompareTo(DateTime.Now) <= 0)
return false;
Thread.Sleep(1000);
}
return true;
}
public static bool IsAlive(int pid, string machine)
{
// doesn't work for me (throws "The network path was not found" exception)
//return Process.GetProcessById(pid, @"\\" + machine) != null;
string user;
string domain;
GetProcessInfoByPID(pid, machine, out user, out domain);
return !string.IsNullOrEmpty(user);
}
public static string GetProcessInfoByPID(int PID, string machine, out string User, out string Domain)
{
// copied from http://www.codeproject.com/KB/cs/processownersid.aspx?fid=323674&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2076667
// with slight modifications
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", machine), connOptions);
manScope.Connect();
User = String.Empty;
Domain = String.Empty;
string OwnerSID = String.Empty;
string processname = String.Empty;
try
{
ObjectQuery sq = new ObjectQuery
("Select * from Win32_Process Where ProcessID = '" + PID + "'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, sq);
if (searcher.Get().Count == 0)
return OwnerSID;
foreach (ManagementObject oReturn in searcher.Get())
{
string[] o = new String[2];
//Invoke the method and populate the o var with the user name and domain
oReturn.InvokeMethod("GetOwner", o);
//int pid = (int)oReturn["ProcessID"];
processname = (string)oReturn["Name"];
//dr[2] = oReturn["Description"];
User = o[0];
if (User == null)
User = String.Empty;
Domain = o[1];
if (Domain == null)
Domain = String.Empty;
string[] sid = new String[1];
oReturn.InvokeMethod("GetOwnerSid", sid);
OwnerSID = sid[0];
return OwnerSID;
}
}
catch
{
return OwnerSID;
}
return OwnerSID;
}
Sysinternals의 PSLIST를 사용하여 원격 컴퓨터를 투표하십시오.
제휴하지 않습니다 StackOverflow