我创建了一个管理应用程序,它还允许快速访问远程计算机的远程桌面会话。我需要等到进程结束,这样我才能关闭到远程服务器的 VPN 连接。一切正常,除了等待进程结束。
以下代码用于启动 MSTSC 进程并等待它结束:
var process = new Process
{
StartInfo = new ProcessStartInfo("mstsc.exe"),
EnableRaisingEvents = true
};
process.Exited += (o, e) => Console.WriteLine("Process stopped.");
process.Start();
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
该Exited事件几乎在程序启动后立即引发。当我mstsc.exe用notepad.exe一切替换时按预期工作。我认为 MSTSC 可能会自己分叉并中止初始过程。
但是可以使用以下命令(来自命令行)等待 MSTSC 结束:
start /wait mstsc.exe
Run Code Online (Sandbox Code Playgroud)
在我退出远程桌面会话之前,此命令不会返回。鉴于这些信息,我用这个替换了我的代码:
var process = new Process
{
StartInfo = new ProcessStartInfo("cmd.exe"),
Arguments = "/c start /wait mstsc.exe",
EnableRaisingEvents = true
};
process.Exited += (o, e) => Console.WriteLine("Process stopped.");
process.Start();
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
这将运行 CMD.exe 并发出start /wait mstsc.exe命令。如果这结束,CMD 过程也会结束,我很好(有一个讨厌的解决方法,但还好)。不幸的是,这不会发生。CMD 进程立即终止。有人知道我做错了什么吗?
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
不起作用,因为 mstsc 在开始时会打开自己的新副本并关闭原始副本。
process.WaitForExit();
process = Process.GetProcessesByName(process.ProcessName).First();
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
会工作,但这是可怕的解决方法。
更新 1:
似乎 mstsc 关闭了原始进程,但不是它的输出流!所以你可以等待进程 StandardOutput 关闭。
var process = new Process
{
StartInfo = new ProcessStartInfo("mstsc.exe") { UseShellExecute = false, RedirectStandardOutput = true }
};
process.Start();
process.StandardOutput.ReadToEnd(); //This will wait for stream to close.
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想阻止当前线程:
var process = new Process
{
StartInfo = new ProcessStartInfo("mstsc.exe") { UseShellExecute = false, RedirectStandardOutput = true }
};
process.Start();
var outputResultPromise = process.StandardOutput.ReadToEndAsync();
outputResultPromise.ContinueWith(o=> Console.WriteLine("Stream closed"));
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3441 次 |
| 最近记录: |