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 Sub DataReceivedEventHandler (
	sender As Object,
	e As DataReceivedEventArgs


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.
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Namespace ProcessAsyncStreamSamples

   Class ProcessAsyncOutputRedirection
      ' Define static variables shared by class methods.
      Private Shared sortOutput As StringBuilder = Nothing
      Private Shared numOutputLines As Integer = 0

      Public Shared Sub SortInputListText()

         ' Initialize the process and its StartInfo properties.
         ' The sort command is a console application that
         ' reads and sorts text input.
         Dim sortProcess As 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.  
         ' Read the stream asynchronously using an event handler.
         sortProcess.StartInfo.RedirectStandardOutput = True
         sortOutput = new StringBuilder()

         ' Set our event handler to asynchronously read the sort output.
         AddHandler sortProcess.OutputDataReceived, _
                    AddressOf 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.
         Dim sortStreamWriter As StreamWriter = 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")

         Dim inputText As String
         Dim numInputLines As Integer = 0
            Console.WriteLine("Enter a text line (or press the Enter key to stop):")

            inputText = Console.ReadLine()
            If Not String.IsNullOrEmpty(inputText) Then
               numInputLines += 1
            End If
         Loop While Not String.IsNullOrEmpty(inputText) AndAlso 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 Not String.IsNullOrEmpty(numOutputLines) Then
            ' 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.")
         End If

      End Sub 

      Private Shared Sub SortOutputHandler(sendingProcess As Object, _
         outLine As DataReceivedEventArgs)

         ' Collect the sort command output.
         If Not String.IsNullOrEmpty(outLine.Data) Then
            numOutputLines += 1

            ' Add the text to the collected output.
            sortOutput.Append(Environment.NewLine + "[" _
                         + numOutputLines.ToString() + "] - " _
                         + outLine.Data)
         End If
      End Sub 
   End Class  
End Namespace 

Namespace ProcessAsyncStreamSamples

   Class ProcessSampleMain

      ' The main entry point for the application.
      Shared Sub Main()

         Catch e As InvalidOperationException
         End Try
      End Sub 'Main
   End Class  'ProcessSampleMain
End Namespace 'Process_AsyncStream_Sample

.NET Framework
Disponible desde 2.0
Volver al principio