0 out of 1 rated this helpful - Rate this topic

Process.OutputDataReceived Event

Updated: March 2011

Occurs when an application writes to its redirected StandardOutput stream.

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)
[BrowsableAttribute(true)]
public event DataReceivedEventHandler OutputDataReceived

The OutputDataReceived event indicates that the associated Process has written to its redirected StandardOutput stream.

The event is enabled during asynchronous read operations on StandardOutput. To start asynchronous read operations, you must redirect the StandardOutput stream of a Process, add your event handler to the OutputDataReceived event, and call BeginOutputReadLine. Thereafter, the OutputDataReceived event signals each time the process writes a line to the redirected StandardOutput stream, until the process exits or calls CancelOutputRead.

Note Note

The application that is processing the asynchronous output should call the WaitForExit() method to ensure that the output buffer has been flushed.

The following example illustrates how to perform asynchronous read operations on the redirected StandardOutput stream of the sort command. The sort command is a console application that reads and sorts text input.

The example creates an event delegate for the SortOutputHandler event handler and associates it with the OutputDataReceived event. The event handler receives text lines from the redirected StandardOutput stream, formats the text, and writes the text to the screen.


// Define the namespaces used by this sample.
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace ProcessAsyncStreamSamples
{
    class SortOutputRedirection
    {
        // Define static variables shared by class methods.
        private static StringBuilder sortOutput = null;
        private static int numOutputLines = 0;

        public static void SortInputListText()
        {
            // Initialize the process and its StartInfo properties.
            // The sort command is a console application that
            // reads and sorts text input.

            Process sortProcess;
            sortProcess = new Process();
            sortProcess.StartInfo.FileName = "Sort.exe";

            // Set UseShellExecute to false for redirection.
            sortProcess.StartInfo.UseShellExecute = false;

            // Redirect the standard output of the sort command.  
            // This stream is read asynchronously using an event handler.
            sortProcess.StartInfo.RedirectStandardOutput = true;
            sortOutput = new StringBuilder("");

            // Set our event handler to asynchronously read the sort output.
            sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);

            // Redirect standard input as well.  This stream
            // is used synchronously.
            sortProcess.StartInfo.RedirectStandardInput = true;

            // Start the process.
            sortProcess.Start();

            // Use a stream writer to synchronously write the sort input.
            StreamWriter sortStreamWriter = sortProcess.StandardInput;

            // Start the asynchronous read of the sort output stream.
            sortProcess.BeginOutputReadLine();

            // Prompt the user for input text lines.  Write each 
            // line to the redirected input stream of the sort command.
            Console.WriteLine("Ready to sort up to 50 lines of text");

            String inputText;
            int numInputLines = 0;
            do 
            {
                Console.WriteLine("Enter a text line (or press the Enter key to stop):");

                inputText = Console.ReadLine();
                if (!String.IsNullOrEmpty(inputText))
                {
                    numInputLines ++;
                    sortStreamWriter.WriteLine(inputText);
                }
            }
            while (!String.IsNullOrEmpty(inputText) && (numInputLines < 50));
            Console.WriteLine("<end of input stream>");
            Console.WriteLine();

            // End the input stream to the sort command.
            sortStreamWriter.Close();

            // Wait for the sort process to write the sorted text lines.
            sortProcess.WaitForExit();

            if (numOutputLines > 0)
            {
                // Write the formatted and sorted output to the console.
                Console.WriteLine(" Sort results = {0} sorted text line(s) ", 
                    numOutputLines);
                Console.WriteLine("----------");
                Console.WriteLine(sortOutput);
            }
            else 
            {
                Console.WriteLine(" No input lines were sorted.");
            }

            sortProcess.Close();
        }

        private static void SortOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
            // Collect the sort command output.
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                numOutputLines++;

                // Add the text to the collected output.
                sortOutput.Append(Environment.NewLine + 
                    "[" + numOutputLines.ToString() + "] - " + outLine.Data);
            }
        }
    }
}

namespace ProcessAsyncStreamSamples
{

    class ProcessSampleMain
    {
        /// The main entry point for the application.
        static void Main()
        {
            try 
            {
                SortOutputRedirection.SortInputListText();
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("Exception:");
                Console.WriteLine(e.ToString());
            }
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • LinkDemand  

    for full trust for the immediate caller. This member cannot be used by partially trusted code.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Date

History

Reason

March 2011

Added information about flushing buffers.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Is this still broken?
$0**Update** This seems to be working fine, make sure your console app write correctly to the console. In my case the WriteConsole was not making this work. But using a good old std::cout makes the messages appear asynchronously on the event. Also make sure to have a fflsuh(stdout) in the console app.$0 $0$0 $0 $0$0 $0 I am trying to make the even fire ASYNCHRONOUSLY but the event doesnt fire at all, until the launched process exits or I close it down manually. In that case I suddenly get a series of event triggers and the messages appearing in the event are in reverse order chronologically. $0$0 $0 $0$0 $0 $0Any idea if this is still working as explained above? My child process is rather time taking and I read that this event doesnt do good with long running process'.$0 $0$0 $0 $0As a test I tried to launch 'ping localhost' as a child PRocess, and in that case the event fires Asynchronously, and messages are in right order...$0 $0$0 $0 $0Any pointers?$0
Event handlers get called on different threads
Please, ad a remark to the doc that the async operations get called on a different thread. This is important if one wants to log output and standard out and standard err fire at the same time. At that point a possible log file will get garbled. Took me a day to track this one down.

A similar message (not from me) appears on the Process.OutputDataReceived Event doc for .net 3.5 (http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived%28v=vs.85%29.aspx)
Event firing on long running processes
Shital, Synch and Async calls cannot be mixed on the same process stream.  But indeed the event will never fire until the process has completed, making it NOT Asynchronous at all.  Others in this forum have discovered this as well.  It is a bug that severely limits functionality and makes this event useless for my purposes.
Event firing
This event may not get fired until process exists. Typically you can employ event handler as well as reading stream manually like this:

//Setup event handler
xCopyProcess.OutputDataReceived += new DataReceivedEventHandler(RedirectedOutputHandler);

//In a loop keep polling at frequent time intervals
if (xCopyProcess.StartInfo.RedirectStandardOutput && !xCopyProcess.StandardOutput.EndOfStream)
AppendToStatusText(xCopyProcess.StandardOutput.ReadToEnd());


//Listen to events
static void RedirectedOutputHandler( Object sender, DataReceivedEventArgs outLine )
{
string message = outLine.Data;
if (!String.IsNullOrEmpty(message))
{
statusRichTextBox.Invoke(new MethodInvoker(
delegate
{
lock (statusMessagesStatic)
{
statusMessagesStatic.AppendText(message);
}
}));
}
}