13

I'm starting a new process using the following code:

Process p = new Process();
p.StartInfo.FileName = "...";
p.StartInfo.Arguments = "...";
p.Start();
p.WaitForExit(300000); // 5 minutes

if (!p.HasExited) 
    p.Kill();
Console.Write(p.ExitCode);

When the process ends within the 5 minutes, that's working, but when it doesn't, I get

InvalidOperationException (Process must exit before requested information can be determined...).

Any idea why I'm getting this exception?

Thank you.

Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
Morgan M.
  • 846
  • 2
  • 9
  • 27
  • Your getting the error because the process must exit before reques... Is this your process? might be worth figuring out why its taking longer than you expect, where does the error occur – Sayse Aug 01 '13 at 14:02
  • No, that's not my process. – Morgan M. Aug 01 '13 at 14:19

2 Answers2

19

According to MSDN, "The Kill method executes asynchronously. After calling the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited."

In other words, just because Kill returns doesn't mean the process is actually gone. You'll need to call WaitForExit to wait until the process has actually disappeared.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
  • 6
    I've had problems with the exception still occurring after `WaitForExit()`, though. Only a `while (!process.HasExited) Thread.Sleep(5);` saved me in the end. You'd think that's exactly what `WaitForExit()` does, but, apparently not. – Nyerguds Feb 13 '15 at 11:54
  • Could be a rare race condition, i.e. the kernel pre-emptively marks the process as exited before finishing cleanup. – Drew McGowen Feb 13 '15 at 19:07
  • 2
    Of course, if all else fails you can always define an `Int32? exitcode = null;` after the `p.WaitForExit()` and then make a `while (!exitCode.HasValue)` loop containing a try-catch which fetches the `p.ExitCode` into that nullable var, catches only InvalidOperationException, and has the 5 millisecond thread sleep in the `catch` part. – Nyerguds Feb 26 '16 at 11:51
-2

Some properties of a Process (such as HasExited) can be determined only after the process has quit. Hence the error.

I would suggest to have a try/catch block to get the exception happening.

Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
  • 3
    It'd be kinda pointless if `HasExited` was avaiable *only after the process has quit*, don't you think? The problem is probably that Kill() isn't a synchronous method, and `ExitCode` isn't avaiable right after calling it since the process isn't actually *dead* yet. – KappaG3 Aug 01 '13 at 14:05
  • 2
    What is the point in the HasExited property if we only can use it when the process has exited? – Morgan M. Aug 01 '13 at 14:16