FOLLOW US
softpcapps Software CODE HELP BLOG

Shareware and free Open Source Windows Software Applications and free Online Tools

How to correctly Read Process Output without freezing

The problem - Wrong way

We want to read the output of an external process. Therefore we redirect standardoutput and we try to read lines from the stream.
The problem is that if we do it as in the following way then if the process does not write anything to the output the program will freeze indefinitely.
	

	// we create the process
	
	Process myproc = new Process();
            
	myproc.StartInfo.FileName = "myprogram";
	myproc.StartInfo.CreateNoWindow = true;
	myproc.StartInfo.UseShellExecute = false;                        
	myproc.StartInfo.RedirectStandardOutput = true;
	myproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
	
	// we start it
	
	myproc.Start();
	
	string line=null;
	
	string myproc_output="";
	
	// we read from the standard output stream but if no output is written from the process it will freeze here
	
	while ((line=myproc.StandardOutput.ReadLine())!=null)
	{
		myproc_output+=line;
	}

 

Solution - Correct way

The correct way is to read the process standard output asynchronously and use the OutputDataReceived event of the process to get the output text.
You can do something like the following :
	

	// variable that holds the output of the process
	private string myproc_output="";
 
	private void ReadProcessOutput()
	{
		// we create the process
		
		Process myproc = new Process();

		myproc.StartInfo.FileName = "myprogram";
		myproc.StartInfo.CreateNoWindow = true;
		myproc.StartInfo.UseShellExecute = false;                        
		myproc.StartInfo.RedirectStandardOutput = true;
		myproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

		// we add the OutputDataReceived event handler
		
		myproc.OutputDataReceived += myproc_OutputDataReceived;

		// we start the process
		
		myproc.Start();

		// we start reading from the Standard Output asynchronously
		
		myproc.BeginOutputReadLine();

		// we wait till the process exits
		
		myproc.WaitForExit();

		myproc.Close();
		
		Console.WriteLine("myproc output="+myproc_output);
	}

	void myproc_OutputDataReceived(object sender, DataReceivedEventArgs e)
	{
		// data was received - we add it to the string variable
		
		myproc_output+=e.Data;
	}