博客园  :: 首页  :: 联系 :: 管理

使用 C# 等待外壳应用程序完成

Posted on 2006-08-11 14:41  sunrack  阅读(1112)  评论(0编辑  收藏  举报

概要

本文演示如何使用 .NET 框架的 Process 类来从您的代码中启动另一个应用程序,并让代码等到此应用程序结束后继续向下执行。

在代码等待应用程序完成时,有两个选择:

无限期等待另一个应用程序完成或由用户关闭。
指定超时期限,过此期限后您可以从代码中将此应用程序关闭。
本文提供了两段代码示例来演示这两种办法。另外,设置超时的示例考虑到另外这一应用程序停止响应(挂起)的可能性,并可采取必要的步骤关闭该应用程序。

要求

Microsoft C# .NET

包括名称空间

您必须导入 Process 类的名称空间,然后才可以运行下面的代码示例。将下面这一行代码放在包含代码示例的 Namespace Class 声明之前:
using System.Diagnostics;

无限期等待外壳应用程序完成

下面的代码示例启动另一个应用程序(本例中是 Notepad),并无限期等待该应用程序关闭。
    //How to Wait for a Shelled Process to Finish
//Get the path to the system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set the file name member of the process info structure.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for the window to finish loading.
p.WaitForInputIdle();
//Wait for the process to end.
p.WaitForExit();
MessageBox.Show("Code continuing...");

为外壳应用程序设置超时

下面的代码示例为外壳应用程序设置了超时。示例中的超时设置为 5 秒。在测试中您可能希望调整此数字(以毫秒计)。
    //Set a time-out value.
int timeOut=5000;
//Get path to system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set file name to open.
pInfo.FileName = sysFolder + @"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for window to finish loading.
p.WaitForInputIdle();
//Wait for the process to exit or time out.
p.WaitForExit(timeOut);
//Check to see if the process is still running.
if (p.HasExited == false)
//Process is still running.
//Test to see if the process is hung up.
if (p.Responding)
//Process was responding; close the main window.
p.CloseMainWindow();
else
//Process was not responding; force the process to close.
p.Kill();
MessageBox.Show("Code continuing...");

疑难解答

有时在这两个方法之间做出选择可能会很困难。设置超时的主要目的是防止您的应用程序因另一个应用程序挂起而停止执行。超时更适合于执行后台处理的外壳应用程序,此时,用户可能不知道该应用程序已停止执行或没有方便的办法关闭。