title: Cancel a process while it is running
body: <p>I run a process that executes an exe in command line with arguments and it takes time to finish. In the meantime, I show a form as dialog with a progress bar and a cancel button. When the cancel button is pressed the process should abort/stop. I have two ways to do it:</p>
  
  <p>A. Declare a public static object of Process class in main form and abort it from progress form when cancel button is clicked:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>And close/abort process from Progress window form:</p>
  
  <pre><code>public partial class frmProgress : Form
  {
      private void btnCancel_Click(object sender, EventArgs e)
      {
          frmMain.Process.Close();
          frmMain.Process.Dispose();
      }
  }
  </code></pre>
  
  <p>B. Or do not call Process.WaitForExit(); and instead use Process.HasExited to check if the process is running and cancel it if cancel button is clicked:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>What is the right way to do it?</p>