在C#中顺序执行多个Process.Start()

4

我在我的C#应用程序中使用Process.Start()执行3个exe文件。我希望按顺序运行所有这些exe文件。目前,每个Process.Start()都是并行执行的。

例如:

Process.Start(exe1ForCopying_A_50_Mb_File);      
Process.Start(exe2ForCopying_A_10_Mb_File);  
Process.Start(exe3ForCopying_A_20_Mb_File);

我希望在第一个Process.Start()完成复制50 Mb文件(需要大约1到2分钟)后再开始执行我的第二个Process.Start()

有什么建议吗?

谢谢。

3个回答

15

我想我自己找到了答案..! :)

Process process = new Process(); 
ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.FileName = MyExe; 
startInfo.Arguments = ArgumentsForMyExe; 
process.StartInfo = startInfo; 
process.Start(); 
process.WaitForExit(); // This is the line which answers my question :) 

感谢VAShhh提供的建议。


0

1
我想我自己找到了答案..! :)Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = MyExe; startInfo.Arguments = ArgumentsForMyExe; process.StartInfo = startInfo; process.Start(); process.WaitForExit(); // 这一行回答了我的问题 :)感谢 VAShhh 的建议。 - Sandeep
如果我理解得正确,您编写的代码使程序“阻塞”或“等待”并行进程的结束。 您确定这不会导致界面冻结吗? 使用事件不会造成这种情况。 - VAShhh

0

你可以启动一个后台线程或任务并在循环中同步等待(使用WaitForExit),或者你可以使用异步方法。

逐个创建Process对象,并将事件处理程序连接到Exited事件,以继续下一个Process。使用Process构造函数创建它们,挂接Exited事件处理程序,然后调用Start;否则,如果进程在Process.Start返回和事件处理程序附加之间失败,我认为事件处理程序不会被调用,因为它已经严格退出了。

概念验证:(不处理Dispose,队列访问不是线程安全的,尽管如果它真的是串行的话,应该足够了,等等)

Queue<Process> ProcessesToRun = new Queue<Process>(new []{ new Process("1"), new Process("2"), new Process("3") });

void ProcessExited(object sender, System.EventArgs e) {
    GrabNextProcessAndRun();
}

void GrabNextProcessAndRun() {
    if (ProcessesToRun.Count > 0) {
        Process process = ProcessesToRun.Dequeue();
        process.Exited += ProcessExited;
        process.Start();
    }
}

void TheEntryPoint() {
    GrabNextProcessAndRun();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接