Redirect lengthy application's output?

  • Thread starter Thread starter Sin Jeong-hun
  • Start date Start date
S

Sin Jeong-hun

Process p = new Process();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardOutput.ReadToEnd();

This works if the application outputs very little amount of string and
exits quickly. But what if the application does a lengthy job and
outputs the progress and my C# application should be notified if the
job is progressed? Should I periodically invoke ReadToEnd() in a while
loop? Seems a waste of cpu cycles. Can't I just get notified when the
application outputs something instead? I tried to search the Internet
myself, but I couldn't find an answer.
 
Sin said:
[...]
p.StandardOutput.ReadToEnd();

This works if the application outputs very little amount of string and
exits quickly. But what if the application does a lengthy job and
outputs the progress and my C# application should be notified if the
job is progressed? [...]

As an alternative to using the OutputDataReceived event mentioned in the
other reply, you may also just use the async methods on the
StandardOutput stream. They will work just as the async methods for
Stream do with other streams, and provide nice asynchronous access to
the data being written to the stream.

You definitely would not want to call ReadToEnd() in a while loop. It
won't complete until the stream has actually ended (is closed), which
occurs when the process exits.

Pete
 
Back
Top