I've a method that contains a process that must be stopped in a deadline( ex: 3 seconds) whether it has finished or not, and I don't want to wait if it has finished executing before reaching that dead line.
using Process.WaitForExit(3000) makes the program wait 3s even if the process has stopped before reaching the limit.
One more thing, I'm using process.StandardOutput.ReadToEnd(); to read the execution result, I don't care if it returns null or empty string or whatever if it doesn't finish.
And I guess that timers will cause the same problem.
Any Ideas?
Asked
Active
Viewed 1,022 times
-1

user3379482
- 557
- 1
- 10
- 21
-
Your statement that `Process.WaitForExit` always waits for the full 3 seconds is not correct. – DavidG Aug 22 '16 at 10:08
-
I have set it to show the result of executing 'dir' cmd command, it waits 3 killing seconds each time – user3379482 Aug 22 '16 at 10:09
-
What command are you passing to it? Whatever you are doing is not exiting properly. For example, to do `dir`, you need to run `cmd` with parameters of `/C dir`. – DavidG Aug 22 '16 at 10:11
-
I know.. Actually without '/c dir' the command won't execute at all – user3379482 Aug 22 '16 at 10:15
-
OK, I've just tested with `cmd` and `/C dir` and a timeout of 10 seconds, it works fine and exits immediately. – DavidG Aug 22 '16 at 10:17
-
could you please post your code as an answer so I can test it and accept it if it worked? – user3379482 Aug 22 '16 at 10:17
1 Answers
0
Exited
event of your process can be handled for detecting exit time.
WaitForExit
returns a Boolean value that indicates your process has reached the timeout before exit or not.
Test this code:
Process proc = new Process();
ProcessStartInfo procInfo = new ProcessStartInfo()
{
FileName = "d:/test.exe",
UseShellExecute = false,
RedirectStandardOutput = true
};
proc.StartInfo = procInfo;
proc.EnableRaisingEvents = true;
proc.Exited += (o, args) =>
{
MessageBox.Show(proc.StandardOutput.ReadToEnd());
};
proc.Start();
if (proc.WaitForExit(3000))
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}

Milad H.
- 122
- 6
-
@user3379482 Nowو by modifying some properties of procInfo the StandardOutput.ReadToEnd can be used in Exited event handler. – Milad H. Aug 22 '16 at 11:29