title: Batch script calling robocopy in Process won't terminate
body: <p>If <code>process.Kill()</code> is called from another thread or even another program, the process never comes out of <code>WaitForExit()</code> if the batch script used robocopy.exe until it is finished as if it wasn't killed.</p>
  
  <p>Robocopy.exe is called from the batch script. Every other script or program ends as you'd expect.</p>
  
  <pre><code>    ProcessStartInfo startInfo = new ProcessStartInfo();
      startInfo.FileName = "batch.bat";
      startInfo.UseShellExecute = false;
      startInfo.CreateNoWindow = true;
      startInfo.RedirectStandardOutput = true;
      startInfo.OutputDataReceived += CaptureHandler;
      startInfo.RedirectStandardError = true;
      startInfo.ErrorDataReceived += CaptureHandler;
      process.Start();
      process.BeginOutputReadLine();
      process.BeginErrorReadLine();
      process.WaitForExit(); 
  </code></pre>
  
  <p>The batch script looks like:</p>
  
  <pre><code>@echo off
  call "robocopy.exe" "somedir" "somedest" /mir /fp /ndl /njh /njs /ns
  </code></pre>
  
  <p>I have a feeling it has to do with the output handlers.
  I tried using <code>process.CancelErrorRead</code> and <code>process.CancelOutputRead()</code> as well after the <code>Kill()</code> call and before, no luck.</p>
  
  <p>Oddly, if you use <code>process.WaitForExit(timeout)</code> overload, it will return true immediately after <code>Kill()</code> from the other thread. However, it's lying. The process is still running! If you try <code>process.WaitForExit()</code> again, as per the MSDN doc, it will still wait for the process to finish despite <code>HasExited</code> saying true.</p>
  
  <blockquote>
    <p>To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter after receiving a true from this overload.</p>
  </blockquote>
  
  <p><a href="https://msdn.microsoft.com/en-us/library/ty0d8k56(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/ty0d8k56(v=vs.110).aspx</a></p>