Search code examples
c#process

C#: Process.HasExited returns false even though the process has terminated


Possibly the inverse of this question: Process.HasExited returns true even though process is running?

I called Kill() on a process and it seems to have exited. But when I test HasExited, I get false:

myProcess.Kill();

while ( !myProcess.HasExited )
{
    Thread.Sleep(1000);
}

And this continues indefinitely. Granted, I have to change this code to stop waiting eventually, but I'm curious as to why HasExited still returns false when the process seems to have dropped off the map so to speak.


Solution

  • Are you redirecting standard output? MSDN states the following:

    When standard output has been redirected to asynchronous event handlers, it is possible that output processing will not have completed when this property returns true. To ensure that asynchronous event handling has been completed, call the WaitForExit() overload that takes no parameter before checking HasExited.

    Anyway, the suggested workaround should possibly do the trick:

    myProcess.Kill();
    myProcess.WaitForExit();