InvalidOperationException with Process
Asked Answered
O

2

14

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.

Olav answered 1/8, 2013 at 13:59 Comment(2)
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 occurHannon
No, that's not my process.Olav
T
20

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.

Timbal answered 1/8, 2013 at 14:3 Comment(3)
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.Rhpositive
Could be a rare race condition, i.e. the kernel pre-emptively marks the process as exited before finishing cleanup.Timbal
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.Rhpositive
T
-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.

Tidy answered 1/8, 2013 at 14:4 Comment(2)
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.Ruano
What is the point in the HasExited property if we only can use it when the process has exited?Olav

© 2022 - 2024 — McMap. All rights reserved.