Search code examples
c#.netprocesswindows-servicesheartbeat

Process.WaitForExit Method Thows InvalidOperation Exception After Process.Close


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.

The problem I was having stemmed from the following 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();
 }

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.

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.

If there is a more elegant solution to this problem, please let me know.


Solution

  • Process.Close doesn't terminate the actual process. It has no effect on the process at all; it just releases the resources of the Process class (after which it is no longer usable, as you discovered)

    If your intention is to end the process, you must use another method such as Process.Kill or Process.CloseMainWindow.

    Process.Close has a different use; you should call that (or Process.Dispose) after you are done with the Process class instance.