Reputation: 783
My goal is to be able to asynchronously read the stdout stream of a process character-at-a-time. My simplified but still failing code is below. Read reads the characters fine until all of them have been read, but when it then goes back for another character it never returns. I'm using Win 8.1 Pro 64-bit, VS2013 Ultimate, and building for .NET 4.5.
Thanks, Ray
public static void RunIt()
{
Process process = new Process();
process.StartInfo.FileName = "D:\\temp\\C1A7E1.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string textString = string.Empty;
for (; ; )
{
int outputCharInt;
if ((outputCharInt = process.StandardOutput.Read()) != -1)
textString += (char)outputCharInt;
else
Thread.Sleep(1000);
}
}
Upvotes: 0
Views: 1331
Reputation: 5305
If you wanna asynchronously read the standard output, you have to handle Prcess.OutputDataReceived
event and use Process.BeginOutputReadLine()
method as follows:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("process file");
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.OutputDataReceived += process_OutputDataReceived;
...
process.Start();
process.BeginOutputReadLine(); // Starts the asynchronous read
private void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
...
}
}
As a reference see: MSDN
Upvotes: 1