如何通过命令行执行命令并等待它完成
问题描述:
我试图通过命令行执行一个命令,然后执行另一个命令(不是在cmd中),它依赖于前一命令的结果。 问题是第一个命令需要大约2分钟才能结束,第二个命令不会“等待”第一个命令结束。 我怎样才能让第二个命令等到第一个结束?如何通过命令行执行命令并等待它完成
在此先感谢!
public void runCmd(){
String command = @"/k java -jar myJava.jar";
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
cmdsi.Arguments = command;
Process cmd = Process.Start(cmdsi);
}
.
.
.
runCmd(); //first command, takes 2 minutes to finish
MessageBox.Show("This Should popup only when runCmd() finishes");
答
使用Process.WaitForExit方法:
public void runCmd()
{
String command = @"/k java -jar myJava.jar";
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
cmdsi.Arguments = command;
Process cmd = Process.Start(cmdsi);
cmd.WaitForExit();
}
.
.
.
runCmd();
MessageBox.Show("This Should popup only when runCmd() finishes");
答
你可以使用WaitForExit()。
注:
-
WaitForExit(int milliseconds)
等待指定的毫秒数为关联的进程退出。 -
WaitForExit()
无限期地等待关联进程退出。
public void runCmd() { String command = @"/k java -jar myJava.jar"; ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe"); cmdsi.Arguments = command; Process cmd = Process.Start(cmdsi); cmd.WaitForExit(); //wait indefinitely for the associated process to exit. } . . . runCmd(); //first command, takes 2 minutes to finish MessageBox.Show("This Should popup only when runCmd() finishes");
答
您可以使用Process.WaitForExit()
方法;
指示进程组件无限期地等待 关联进程退出。
// Start the process with the info you specified.
// Call WaitForExit and then the using statement will close.
using(Process cmd = Process.Start(cmdsi))
{
cmd.WaitForExit();
}
答
使用WaitForExit();
过程将是最好的,因为其他人说。
指定命令以毫秒为单位退出或无限期建议的时间。