我运行一个在命令行中使用参数执行 exe 的进程,它需要时间才能完成。同时,我将表单显示为带有进度条和取消按钮的对话框。当按下取消按钮时,该过程应该中止/停止。我有两种方法可以做到:
A. 在主窗体中声明 Process 类的公共静态对象,并在单击取消按钮时将其从进度窗体中止:
public partial class frmMain : Form
{
public static Process Process = new Process();
public static bool ExecuteCommand(string sCommandLineFile, string sArguments)
{
Process.StartInfo.FileName = sCommandLineFile;
Process.StartInfo.Arguments = sArguments;
Process.StartInfo.CreateNoWindow = true;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
Process.Start();
Process.WaitForExit();
}
}
并从进度窗口窗体关闭/中止进程:
public partial class frmProgress : Form
{
private void btnCancel_Click(object sender, EventArgs e)
{
frmMain.Process.Close();
frmMain.Process.Dispose();
}
}
B. 或者不调用 Process.WaitForExit(); 而是使用 Process.HasExited 检查进程是否正在运行,如果单击取消按钮则取消它:
public static bool IsCancelled = false;
Process.StartInfo.FileName = sCommandLineFile;
Process.StartInfo.Arguments = sArguments;
Process.StartInfo.CreateNoWindow = true;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
while (!Process.HasExited)
{
Thread.Sleep(100);
Application.DoEvents();
if (IsCancelled)
{
Process.Close();
Process.Dispose();
}
}
public partial class frmProgress : Form
{
private void btnCancel_Click(object sender, EventArgs e)
{
frmMain.IsCancelled = true;
}
}
正确的方法是什么?