Process.OutputDataReceived Evento
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Ocorre sempre que uma aplicação escreve uma linha no seu fluxo redirecionado StandardOutput .
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
Exemplos
O exemplo seguinte ilustra como realizar operações de leitura assíncronas no fluxo redirecionado StandardOutput do ipconfig comando.
O exemplo cria um delegado de evento para o OutputHandler gestor de eventos e associa-o ao OutputDataReceived evento. O gestor de eventos recebe linhas de texto do fluxo redirecionado StandardOutput , formata o texto e guarda-o numa string de saída que é posteriormente mostrada na janela de consola do exemplo.
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
Observações
O OutputDataReceived evento indica que o associado Process escreveu uma linha terminada com uma nova linha (retorno de transmissão (CR), alimentação de linha (LF) ou CR+LF) para o seu fluxo redirecionado StandardOutput .
O evento é ativado durante operações de leitura assíncronas em StandardOutput. Para iniciar operações de leitura assíncronas, deve redirecionar o StandardOutput fluxo de um Process, adicionar o seu gestor de eventos ao OutputDataReceived evento, e chamar BeginOutputReadLine. A partir daí, o OutputDataReceived evento sinaliza cada vez que o processo escreve uma linha no fluxo redirecionado StandardOutput , até que o processo saia ou chame CancelOutputRead.
Note
A aplicação que processa a saída assíncrona deve chamar o WaitForExit método para garantir que o buffer de saída foi limpo.