title: Process.WaitForExit Method Thows InvalidOperation Exception After Process.Close
body: <p>I am working on a project which relies on a monitoring service (in the form of a windows service) which checks for a simple TCP heartbeat from the main service.  Whenever a heartbeat is not detected for a certain time period, or no main service process is detected at all, it fires up a new one.  To ensure that only one main service is running at a time, it also will close all currently running process by the same name before starting the new instance.</p>
  
  <p>The problem I was having stemmed from the following code:</p>
  
  <pre><code> var processes = from p in Process.GetProcessesByName("Acme") select p;
  
   foreach (var process in processes)
   {
       ...
  
       process.Close();
  
       process.WaitForExit(10000);
       if (!process.HasExited)
           process.Kill();
   }
  </code></pre>
  
  <p>Because the process.Close() method released all resources associated with that process, the WaitForExit() method threw an exception.  I didn't want to just Kill() the process straight away as I wanted the cleanup methods to fire in the main service on close.</p>
  
  <p>The solution for my problem was to call process.CloseMainWindow() in the place of process.Close() which called all of the associated clean up methods and did not release the resources until after the WaitForExit() method.</p>
  
  <p>If there is a more elegant solution to this problem, please let me know.</p>