Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.

Delegado DataReceivedEventHandler


Publicado: octubre de 2016

Representa el método que controlará los eventos OutputDataReceived o ErrorDataReceived de un Process.

Espacio de nombres:   System.Diagnostics
Ensamblado:  System (en System.dll)

public delegate void DataReceivedEventHandler(
	object sender,
	DataReceivedEventArgs e


Type: System.Object

Origen del evento.

Type: System.Diagnostics.DataReceivedEventArgs

Objeto DataReceivedEventArgs que contiene los datos del evento.

When you create a T:System.Diagnostics.DataReceivedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Handling and Raising Events.

To asynchronously collect the redirected P:System.Diagnostics.Process.StandardOutput or P:System.Diagnostics.Process.StandardError stream output of a process, add your event handler to the E:System.Diagnostics.Process.OutputDataReceived or E:System.Diagnostics.Process.ErrorDataReceived event. These events are raised each time the process writes a line to the corresponding redirected stream. When the redirected stream is closed, a null line is sent to the event handler. Ensure that your event handler checks for this condition before accessing the P:System.Diagnostics.DataReceivedEventArgs.Data property. For example, you can use the static method M:System.String.IsNullOrEmpty(System.String) to validate the P:System.Diagnostics.DataReceivedEventArgs.Data property in your event handler.

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

The example creates a T:System.Diagnostics.DataReceivedEventHandler delegate for the SortOutputHandler event handler and associates the delegate with the E:System.Diagnostics.Process.OutputDataReceived event. The event handler receives text lines from the redirected P:System.Diagnostics.Process.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.

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

            // Start the asynchronous read of the sort output stream.

            // 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;
                Console.WriteLine("Enter a text line (or press the Enter key to stop):");

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

            // End the input stream to the sort command.

            // Wait for the sort process to write the sorted text lines.

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


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

                // 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()
            catch (InvalidOperationException e)

.NET Framework
Disponible desde 2.0
Volver al principio