This has been kind of a "criminal research" with very surprising outcome - at least to me.
We are running external commands using a Process object. We are capturing standard output (and standard error - I have removed this from the sample for clarity reasons) asynchronously. This has been answered several times here. The code looks like this and works fine:
var process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = @"...\TestApp.exe"
}
};
process.OutputDataReceived += Process_OutputDataReceived;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.OutputDataReceived -= Process_OutputDataReceived;
Now, what if I want to add a hard timeout to the WaitForExit()
? Easy: there's an overloaded version of WaitForExit(int milliseconds)
. So a call like this should do:
process.WaitForExit(60000);
Now, this renders the output capture incomplete in some cases.
This is not a secret, at least not to Microsoft's developers. After several hours of research, I came to the conclusion that something must be wrong with WaitForExit's implementation. So I took a look into the code and I found this comment in Microsoft's implementation:
// If we have a hard timeout, we cannot wait for the streams
Here's my question - and I have done quite some effort of evaluation without success:
How can I have a hard timeout on WaitForExit()
and at the same time make sure that the console output capture is complete?