Process.BeginOutputReadLine Método

Definición

Comienza las operaciones de lectura asincrónicas en el flujo de StandardOutput redirigido de la aplicación.

public:
 void BeginOutputReadLine();
[System.Runtime.InteropServices.ComVisible(false)]
public void BeginOutputReadLine();
public void BeginOutputReadLine();
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.BeginOutputReadLine : unit -> unit
member this.BeginOutputReadLine : unit -> unit
Public Sub BeginOutputReadLine ()
Atributos

Excepciones

La RedirectStandardOutput propiedad es false.

O bien

Una operación de lectura asincrónica ya está en curso en la StandardOutput secuencia.

O bien

La StandardOutput secuencia la ha usado una operación de lectura sincrónica.

Ejemplos

En el ejemplo siguiente se muestra cómo realizar operaciones de lectura asincrónicas en el flujo redirigido StandardOutput del sort comando. El sort comando es una aplicación de consola que lee y ordena la entrada de texto.

En el ejemplo se crea un delegado de eventos para el SortOutputHandler 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 escribe el texto en la pantalla.

// 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 = 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 += SortOutputHandler;

            // Redirect standard input as well.  This stream
            // is used synchronously.
            sortProcess.StartInfo.RedirectStandardInput = true;

            // Start the process.
            sortProcess.Start();

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

            // Start the asynchronous read of the sort output stream.
            sortProcess.BeginOutputReadLine();

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

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

            // End the input stream to the sort command.
            sortStreamWriter.Close();

            // Wait for the sort process to write the sorted text lines.
            sortProcess.WaitForExit();

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

            sortProcess.Close();
        }

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

                // Add the text to the collected output.
                sortOutput.Append(Environment.NewLine +
                    $"[{numOutputLines}] - {outLine.Data}");
            }
        }
    }
}

namespace ProcessAsyncStreamSamples
{

    class ProcessSampleMain
    {
        /// The main entry point for the application.
        static void Main()
        {
            try
            {
                SortOutputRedirection.SortInputListText();
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("Exception:");
                Console.WriteLine(e);
            }
        }
    }
}
// Define the namespaces used by this sample.
open System
open System.Text
open System.Diagnostics

// Define variables shared by class methods.
let mutable sortOutput = StringBuilder()
let mutable numOutputLines = 0;

let sortOutputHandler (sendingProcess: obj) (outLine: DataReceivedEventArgs) =
    // Collect the sort command output.
    if String.IsNullOrEmpty outLine.Data |> not then
        numOutputLines <- numOutputLines + 1
        // Add the text to the collected output.
        sortOutput.Append(Environment.NewLine + $"[{numOutputLines}] - {outLine.Data}") |> ignore

let sortInputListText () =
    // Initialize the process and its StartInfo properties.
    // The sort command is a console application that
    // reads and sorts text input.

    let 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 <- StringBuilder();

    // Set our event handler to asynchronously read the sort output.
    sortProcess.OutputDataReceived.AddHandler sortOutputHandler

    // Redirect standard input as well.  This stream
    // is used synchronously.
    sortProcess.StartInfo.RedirectStandardInput <- true;

    // Start the process.
    sortProcess.Start() |> ignore

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

    // Start the asynchronous read of the sort output stream.
    sortProcess.BeginOutputReadLine();

    // Prompt the user for input text lines.  Write each
    // line to the redirected input stream of the sort command.
    printfn "Ready to sort up to 50 lines of text"

    let mutable inputText = ""
    let mutable numInputLines = 0
    while String.IsNullOrEmpty inputText do
        printfn "Enter a text line (or press the Enter key to stop):"

        inputText <- Console.ReadLine()
        if String.IsNullOrEmpty inputText |> not then
            numInputLines <- numInputLines + 1
            sortStreamWriter.WriteLine inputText

    printfn "<end of input stream>\n"

    // End the input stream to the sort command.
    sortStreamWriter.Close()

    // Wait for the sort process to write the sorted text lines.
    sortProcess.WaitForExit()

    if numOutputLines > 0 then
        // Write the formatted and sorted output to the console.
        printfn $" Sort results = {numOutputLines} sorted text line(s) "
        printfn "----------"
        printfn $"{sortOutput}"
    else
        printfn " No input lines were sorted."

    sortProcess.Close();

// The main entry point for the application.
do
    try
        sortInputListText ()
    with :? InvalidOperationException as e ->
        printfn "Exception:"
        printfn $"{e}"
' Define the namespaces used by this sample.
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel

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.
            sortProcess.Start()

            ' 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.
            sortProcess.BeginOutputReadLine()

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

                inputText = Console.ReadLine()
                If Not String.IsNullOrEmpty(inputText) Then
                    numInputLines += 1
                    sortStreamWriter.WriteLine(inputText)
                End If
            Loop While Not String.IsNullOrEmpty(inputText) AndAlso numInputLines < 50
            Console.WriteLine("<end of input stream>")
            Console.WriteLine()

            ' End the input stream to the sort command.
            sortStreamWriter.Close()

            ' Wait for the sort process to write the sorted text lines.
            sortProcess.WaitForExit()

            If Not String.IsNullOrEmpty(numOutputLines) Then
                ' Write the formatted and sorted output to the console.
                Console.WriteLine($" Sort results = {numOutputLines} sorted text line(s) ")
                Console.WriteLine("----------")
                Console.WriteLine(sortOutput)
            Else
                Console.WriteLine(" No input lines were sorted.")
            End If

            sortProcess.Close()
        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}] - {outLine.Data}")
            End If
        End Sub
    End Class
End Namespace

Namespace ProcessAsyncStreamSamples

    Class ProcessSampleMain

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

            Catch e As InvalidOperationException
                Console.WriteLine("Exception:")
                Console.WriteLine(e)
            End Try
        End Sub
    End Class  'ProcessSampleMain
End Namespace 'Process_AsyncStream_Sample

Comentarios

La StandardOutput secuencia se puede leer de forma sincrónica o asincrónica. Métodos como Read, ReadLiney ReadToEnd realizan operaciones de lectura sincrónicas en el flujo de salida del proceso. Estas operaciones de lectura sincrónicas no se completan hasta que las escrituras asociadas Process a su StandardOutput secuencia o cierran la secuencia.

En cambio, BeginOutputReadLine inicia operaciones de lectura asincrónicas en la StandardOutput secuencia. Este método habilita un controlador de eventos designado para la salida del flujo y vuelve inmediatamente al autor de la llamada, que puede realizar otro trabajo mientras la salida de la secuencia se dirige al controlador de eventos.

Siga estos pasos para realizar operaciones de lectura asincrónicas en StandardOutput para :Process

  1. Establece UseShellExecute en false.

  2. Establece RedirectStandardOutput en true.

  3. Agregue el controlador de eventos al OutputDataReceived evento. El controlador de eventos debe coincidir con la System.Diagnostics.DataReceivedEventHandler firma del delegado.

  4. Inicie el Process.

  5. Llame a BeginOutputReadLine para .Process Esta llamada inicia operaciones de lectura asincrónicas en StandardOutput.

Cuando se inician las operaciones de lectura asincrónica, se llama al controlador de eventos cada vez que el asociado Process escribe una línea de texto en su StandardOutput secuencia.

Puede cancelar una operación de lectura asincrónica llamando a CancelOutputRead. El autor de la llamada o el controlador de eventos pueden cancelar la operación de lectura. Después de cancelar, puede llamar de BeginOutputReadLine nuevo para reanudar las operaciones de lectura asincrónicas.

Note

No se pueden combinar operaciones de lectura asincrónicas y sincrónicas en un flujo redirigido. Una vez que el flujo redirigido de se Process abre en modo asincrónico o sincrónico, todas las operaciones de lectura adicionales de esa secuencia deben estar en el mismo modo. Por ejemplo, no siga BeginOutputReadLine con una llamada a ReadLine en la StandardOutput secuencia o viceversa. Sin embargo, puede leer dos secuencias diferentes en modos diferentes. Por ejemplo, puede llamar a y, a continuación, llamar BeginOutputReadLine a ReadLine para la StandardError secuencia.

Se aplica a

Consulte también