Process.HasExited returns true even though process is running?

后端 未结 11 2038
忘掉有多难
忘掉有多难 2020-12-15 03:41

I have been observing that Process.HasExited sometimes returns true even though the process is still running.

My code below starts a proces

11条回答
  •  时光说笑
    2020-12-15 04:00

    As per MSDN documentation for HasExited.

    If a handle is open to the process, the operating system releases the process memory when the process has exited, but retains administrative information about the process, such as the handle, exit code, and exit time.

    Probably not related, but it's worth noting.

    If it's only a problem 1/10 of the time, and the process disappears after a second anyway, depending on your usage of HasExited, try just adding another delay after the HasExited check works, like

    while (!process.HasExited)
        DoStuff();
    Thread.Sleep(500);
    Cleanup();
    

    and see if the problem persists.

    Personally, I've always just used the Exited event handler instead of any kind of polling, and a simplistic custom wrapper around System.Diagnostics.Process to handle things like thread safety, wrapping a call to CloseMainWindow() followed by WaitForExit(timeout) and finally Kill(), logging, et cetera, and never encountered a problem.

提交回复
热议问题