Click here to Skip to main content
15,906,219 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
I have this method to execute commands
private static int ExecuteCommand(string command, int timeout)
       {
           var processInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
           {
               CreateNoWindow = true,
               UseShellExecute = false,
               WorkingDirectory = "C:\\",
           };

           var process = Process.Start(processInfo);
           process.WaitForExit(timeout);
           var exitCode = process.ExitCode;
           process.Close();

           return exitCode;
       }


some times i get an exception in
var exitCode = process.ExitCode;


the exception is:
Process must exit before requested information can be determined.
Posted
Comments
Sergey Alexandrovich Kryukov 27-Jul-15 17:18pm    
This is not "access timeout"; such expression does not make much sense.
—SA

1 solution

All right, very nice. But it means you don't need this process.ExitCode value, because it makes no sense at the moment of the call. What's wrong with that? You can use this very condition, the fact of having this exception, to tell the state of the process: sandwich this property call in try-catch block and see if you have this exception. :-)

More seriously, you can do it by checking process.HasExited in advance: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited%28v=vs.110%29.aspx[^].

You see, you call process.WaitForExit(timeout); is apparently a blocking call. It puts the calling thread in a wait state: the system switches out your thread and does not schedule it back to execution until it is waken up, it wastes no CPU time for the wait. The thread can be waken up by a number of reasons, and one of them is timeout. So, when the execution goes past to the call, you don't know exact reason of waking up. You can find it out by checking up the process status.

By the way, in interactive UI applications it would be the reason to execute such things in a separate thread, not a UI thread.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900