The StandardOutput stream can be read synchronously or asynchronously. Methods such as Read, ReadLine, and ReadToEnd perform synchronous read operations on the output stream of the process. These synchronous read operations do not complete until the associated Process writes to its StandardOutput stream, or closes the stream.
In contrast, BeginOutputReadLine starts asynchronous read operations on the StandardOutput stream. This method enables a designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.
Follow these steps to perform asynchronous read operations on StandardOutput for a Process :
Set UseShellExecute to false.
Set RedirectStandardOutput to true.
Add your event handler to the OutputDataReceived event. The event handler must match the System.Diagnostics..::.DataReceivedEventHandler delegate signature.
Start the Process.
Call BeginOutputReadLine for the Process. This call starts asynchronous read operations on StandardOutput.
When asynchronous read operations start, the event handler is called each time the associated Process writes a line of text to its StandardOutput stream.
You can cancel an asynchronous read operation by calling CancelOutputRead. The read operation can be canceled by the caller or by the event handler. After canceling, you can call BeginOutputReadLine again to resume asynchronous read operations.
Note: |
|---|
You cannot mix asynchronous and synchronous read operations on a redirected stream. Once the redirected stream of a Process is opened in either asynchronous or synchronous mode, all further read operations on that stream must be in the same mode. For example, do not follow BeginOutputReadLine with a call to ReadLine on the StandardOutput stream, or vice versa. However, you can read two different streams in different modes. For example, you can call BeginOutputReadLine and then call ReadLine for the StandardError stream. |