Process.OutputDataReceived Evento
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Se produce cada vez que una aplicación escribe una línea en su flujo de StandardOutput redirigido.
public:
event System::Diagnostics::DataReceivedEventHandler ^ OutputDataReceived;
[System.ComponentModel.Browsable(true)]
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived;
[<System.ComponentModel.Browsable(true)>]
member this.OutputDataReceived : System.Diagnostics.DataReceivedEventHandler
Public Custom Event OutputDataReceived As DataReceivedEventHandler
Public Event OutputDataReceived As DataReceivedEventHandler
Tipo de evento
- Atributos
Ejemplos
En el ejemplo siguiente se muestra cómo realizar operaciones de lectura asincrónicas en el flujo redirigido StandardOutput del ipconfig comando.
En el ejemplo se crea un delegado de eventos para el OutputHandler controlador de eventos y se asocia al OutputDataReceived evento. El controlador de eventos recibe líneas de texto de la secuencia redirigida StandardOutput , da formato al texto y la guarda en una cadena de salida que se muestra más adelante en la ventana de consola del ejemplo.
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
class StandardAsyncOutputExample
{
private static int lineCount = 0;
private static StringBuilder output = new StringBuilder();
public static void Main()
{
Process process = new Process();
process.StartInfo.FileName = "ipconfig.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
// Prepend line numbers to each line of the output.
if (!String.IsNullOrEmpty(e.Data))
{
lineCount++;
output.Append("\n[" + lineCount + "]: " + e.Data);
}
});
process.Start();
// Asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.WaitForExit();
// Write the redirected output to this application's window.
Console.WriteLine(output);
process.WaitForExit();
process.Close();
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}
}
open System
open System.Diagnostics
open System.Text
let mutable lineCount = 0
let output = StringBuilder()
let proc = new Process()
proc.StartInfo.FileName <- "ipconfig.exe"
proc.StartInfo.UseShellExecute <- false
proc.StartInfo.RedirectStandardOutput <- true
proc.OutputDataReceived.AddHandler(
DataReceivedEventHandler(fun _ e ->
// Prepend line numbers to each line of the output.
if not (String.IsNullOrEmpty e.Data) then
lineCount <- lineCount + 1
output.Append $"\n[{lineCount}]: {e.Data}" |> ignore)
)
proc.Start() |> ignore
// Asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
proc.BeginOutputReadLine()
proc.WaitForExit()
// Write the redirected output to this application's window.
printfn $"{output}"
proc.WaitForExit()
proc.Close()
printfn "\n\nPress any key to exit."
stdin.ReadLine() |> ignore
Imports System.IO
Imports System.Diagnostics
Imports System.Text
Module Module1
Dim lineCount As Integer = 0
Dim output As StringBuilder = New StringBuilder()
Sub Main()
Dim process As New Process()
process.StartInfo.FileName = "ipconfig.exe"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
AddHandler process.OutputDataReceived, AddressOf OutputHandler
process.Start()
' Asynchronously read the standard output of the spawned process.
' This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine()
process.WaitForExit()
Console.WriteLine(output)
process.WaitForExit()
process.Close()
Console.WriteLine(Environment.NewLine + Environment.NewLine + "Press any key to exit.")
Console.ReadLine()
End Sub
Sub OutputHandler(sender As Object, e As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(e.Data) Then
lineCount += 1
' Add the text to the collected output.
output.Append(Environment.NewLine + "[" + lineCount.ToString() + "]: " + e.Data)
End If
End Sub
End Module
Comentarios
El OutputDataReceived evento indica que el asociado Process ha escrito una línea que finaliza con una nueva línea (retorno de carro (CR), avance de línea (LF) o CR+LF) en su secuencia redirigida StandardOutput .
El evento está habilitado durante las operaciones de lectura asincrónicas en StandardOutput. Para iniciar operaciones de lectura asincrónicas, debe redirigir la StandardOutput secuencia de un Process, agregar el controlador de eventos al evento y llamar a OutputDataReceivedBeginOutputReadLine. Después, el OutputDataReceived evento indica cada vez que el proceso escribe una línea en la secuencia redirigida StandardOutput , hasta que el proceso sale o llama a CancelOutputRead.
Note
La aplicación que procesa la salida asincrónica debe llamar al WaitForExit método para asegurarse de que se ha vaciado el búfer de salida.