InvalidOperationException with process

I am 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 completes within 5 minutes, it works, but when it is not, I get

InvalidOperationException (the process must exit before the request information can be determined ...).

Any idea why I get this exception?

Thanks.

+4
source share
2 answers

According to MSDN , the Kill method runs 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 returning Kill does not mean that the process has actually disappeared. You need to call WaitForExit to wait until the process disappears.

+10
source

Some properties of the process (such as HasExited) can only be determined after the process is complete. Hence the error.

I would suggest having a try / catch block to get an exception.

-one
source

Source: https://habr.com/ru/post/1494751/


All Articles