Process.OutputDataReceived Evento

Definizione

Si verifica ogni volta che un'applicazione scrive una riga nel flusso StandardOutput reindirizzato.

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 evento

Attributi

Esempio

Nell'esempio seguente viene illustrato come eseguire operazioni di lettura asincrone nel flusso reindirizzato StandardOutput del ipconfig comando.

Nell'esempio viene creato un delegato di evento per il OutputHandler gestore eventi e lo associa all'evento OutputDataReceived . Il gestore eventi riceve righe di testo dal flusso reindirizzato StandardOutput , formatta il testo e lo salva in una stringa di output visualizzata più avanti nella finestra della console dell'esempio.

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

Commenti

L'evento OutputDataReceived indica che l'oggetto associato Process ha scritto una riga terminata con una nuova riga (ritorno a capo), avanzamento riga (LF) o CR+LF) nel flusso reindirizzato StandardOutput .

L'evento viene abilitato durante le operazioni di lettura asincrone su StandardOutput. Per avviare operazioni di lettura asincrone, è necessario reindirizzare il flusso di un Processoggetto , aggiungere il StandardOutput gestore eventi all'evento OutputDataReceived e chiamare BeginOutputReadLine. Successivamente, l'evento OutputDataReceived segnala ogni volta che il processo scrive una riga nel flusso reindirizzato StandardOutput , fino a quando il processo non esce o chiama CancelOutputRead.

Note

L'applicazione che elabora l'output asincrono deve chiamare il WaitForExit metodo per assicurarsi che il buffer di output sia stato scaricato.

Si applica a

Vedi anche