6
我运行了一个进程,该进程在带有参数的命令行中执行一个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;
}
}
什么是做正确的方式?
无需轮询'Process.HasExited'只需执行'frmMain.Process.CanRaiseEvents = true',然后订阅[Exited](https://msdn.microsoft.com/en-us/library/system.diagnostics .process.exited(v = vs.110).aspx)事件。 –