【发布时间】:2011-03-10 00:59:14
【问题描述】:
我有一个应用程序
Process.Start()
启动另一个应用程序“ABC”。我想等到该应用程序结束(进程终止)并继续执行。我该怎么做?
可能同时运行应用程序“ABC”的多个实例。
【问题讨论】:
-
如果您想异步执行(即在完成后引发事件),您可以在 SO 处 look here。
我有一个应用程序
Process.Start()
启动另一个应用程序“ABC”。我想等到该应用程序结束(进程终止)并继续执行。我该怎么做?
可能同时运行应用程序“ABC”的多个实例。
【问题讨论】:
我想你只是想要这个:
var process = Process.Start(...);
process.WaitForExit();
方法见MSDN page。它还有一个重载,您可以在其中指定超时,因此您不会永远等待。
【讨论】:
使用Process.WaitForExit?或者如果您不想阻止,请订阅Process.Exited 事件?如果这不能满足您的要求,请向我们提供有关您的要求的更多信息。
【讨论】:
WaitForExit...在某些情况下,您可能希望在某事完成时执行更多代码,但这并不意味着您需要阻止当前线程。
Process.Exited事件,我相信你必须通过将Process.EnableRaisingEvents设置为true来预先配置过程。不过,考虑到这个问题已有三年多的历史了,Process.EnableRaisingEvents 在被问到时可能不是一个东西。
Process.Exited 事件的名称。谢谢! +1 完整性
Process.EnableRaisingEvents 会抛出Win32Exception(拒绝访问)(HasExited 也是如此)。 (至少从 .NET Framework 4.8 开始仍然如此。)
我在我的应用程序中执行以下操作:
Process process = new Process();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.ErrorDialog = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.Start();
process.WaitForExit(1000 * 60 * 5); // Wait up to five minutes.
其中有一些您可能会发现有用的额外功能...
【讨论】:
您可以使用等待退出,或者您可以捕获 HasExited 属性并更新您的 UI 以使用户保持“知情”(期望管理):
System.Diagnostics.Process process = System.Diagnostics.Process.Start("cmd.exe");
while (!process.HasExited)
{
//update UI
}
//done
【讨论】:
我有一个案例,Process.HasExited 在关闭属于该进程的窗口后没有改变。所以Process.WaitForExit() 也没有用。我必须监视 Process.Responding 在像这样关闭窗口后变为假:
while (!_process.HasExited && _process.Responding) {
Thread.Sleep(100);
}
...
也许这对某人有帮助。
【讨论】:
Process.WaitForExit 应该正是我认为您正在寻找的东西。
【讨论】:
最好设置:
myProcess.EnableRaisingEvents = true;
否则代码将被阻止。 也不需要额外的属性。
// Start a process and raise an event when done.
myProcess.StartInfo.FileName = fileName;
// Allows to raise event when the process is finished
myProcess.EnableRaisingEvents = true;
// Eventhandler wich fires when exited
myProcess.Exited += new EventHandler(myProcess_Exited);
// Starts the process
myProcess.Start();
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
Console.WriteLine(
$"Exit time : {myProcess.ExitTime}\n" +
$"Exit code : {myProcess.ExitCode}\n" +
$"Elapsed time : {elapsedTime}");
}
【讨论】:
就像 Jon Skeet 所说,使用Process.Exited:
proc.StartInfo.FileName = exportPath + @"\" + fileExe;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inProcess = true;
while (inProcess)
{
proc.Refresh();
System.Threading.Thread.Sleep(10);
if (proc.HasExited)
{
inProcess = false;
}
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
inProcess = false;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\n", proc.ExitTime, proc.ExitCode);
}
【讨论】:
试试这个:
string command = "...";
var process = Process.Start(command);
process.WaitForExit();
【讨论】: