Process.BeginOutputReadLine Process.BeginOutputReadLine Process.BeginOutputReadLine Process.BeginOutputReadLine Method

Definizione

Inizia le operazioni di lettura asincrona sul flusso StandardOutput reindirizzato dell'applicazione.Begins asynchronous read operations on the redirected StandardOutput stream of the application.

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

Eccezioni

La proprietà RedirectStandardOutput è false.The RedirectStandardOutput property is false.

In alternativa-or- È già in corso un'operazione di lettura asincrona sul flusso StandardOutput.An asynchronous read operation is already in progress on the StandardOutput stream.

In alternativa-or- Il flusso StandardOutput è stato usato da un'operazione di lettura sincrona.The StandardOutput stream has been used by a synchronous read operation.

Esempi

L'esempio seguente illustra come eseguire operazioni di lettura asincrona sul reindirizzato StandardOutput flusso dei sort comando.The following example illustrates how to perform asynchronous read operations on the redirected StandardOutput stream of the sort command. Il sort comando è un'applicazione console che legge e ordina il testo immesso.The sort command is a console application that reads and sorts text input.

Nell'esempio viene creato un delegato per il SortOutputHandler gestore dell'evento e la associa il OutputDataReceived evento.The example creates an event delegate for the SortOutputHandler event handler and associates it with the OutputDataReceived event. Il gestore eventi riceve le righe di testo da reindirizzato StandardOutput flusso, formatta il testo e scrive il testo sullo schermo.The event handler receives text lines from the redirected StandardOutput stream, formats the text, and writes the text to the screen.

// Define the namespaces used by this sample.
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace System::ComponentModel;

ref class SortOutputRedirection
{
private:
   // Define static variables shared by class methods.
   static StringBuilder^ sortOutput = nullptr;
   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;
      sortProcess = gcnew 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 = gcnew StringBuilder;
      
      // Set our event handler to asynchronously read the sort output.
      sortProcess->OutputDataReceived += gcnew DataReceivedEventHandler( 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 = {0} sorted text line(s) ",
            numOutputLines.ToString() );
         Console::WriteLine( "----------" );
         Console::WriteLine( sortOutput->ToString() );
      }
      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->AppendFormat( "\n[{0}] {1}",
            numOutputLines.ToString(), outLine->Data );
      }
   }
};

/// The main entry point for the application.
void main()
{
   try
   {
      SortOutputRedirection::SortInputListText();
   }
   catch ( InvalidOperationException^ e ) 
   {
      Console::WriteLine( "Exception:" );
      Console::WriteLine( e );
   }
}
// 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.
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.
            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 'Main
    End Class  'ProcessSampleMain
End Namespace 'Process_AsyncStream_Sample

Commenti

Il StandardOutput flusso può essere letto in modo sincrono o asincrono.The StandardOutput stream can be read synchronously or asynchronously. I metodi come Read, ReadLine, e ReadToEnd eseguire operazioni di lettura sincrone nel flusso di output del processo.Methods such as Read, ReadLine, and ReadToEnd perform synchronous read operations on the output stream of the process. Questi sincrono letti operazioni non vengono completate finché l'oggetto associato Process scrive relativo StandardOutput streaming, o chiude il flusso.These synchronous read operations do not complete until the associated Process writes to its StandardOutput stream, or closes the stream.

Al contrario, BeginOutputReadLine operazioni di lettura asincrona viene avviata nel StandardOutput flusso.In contrast, BeginOutputReadLine starts asynchronous read operations on the StandardOutput stream. Questo metodo consente a un gestore eventi designato per l'output del flusso e torna immediatamente al chiamante, che può eseguire altre operazioni mentre il flusso output viene indirizzato al gestore dell'evento.This method enables a designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.

Seguire questi passaggi per eseguire operazioni di lettura asincrone sul StandardOutput per un Process :Follow these steps to perform asynchronous read operations on StandardOutput for a Process :

  1. Impostare UseShellExecute su false.Set UseShellExecute to false.

  2. Impostare RedirectStandardOutput su true.Set RedirectStandardOutput to true.

  3. Aggiungere il gestore eventi per il OutputDataReceived evento.Add your event handler to the OutputDataReceived event. Il gestore dell'evento deve corrispondere il System.Diagnostics.DataReceivedEventHandler firma del delegato.The event handler must match the System.Diagnostics.DataReceivedEventHandler delegate signature.

  4. Avviare il Process.Start the Process.

  5. Chiamare BeginOutputReadLine per il Process.Call BeginOutputReadLine for the Process. Questa chiamata inizia le operazioni di lettura asincrone sul StandardOutput.This call starts asynchronous read operations on StandardOutput.

Quando start operazioni di lettura asincrona, il gestore eventi viene chiamato ogni volta che l'oggetto associato Process scrive una riga di testo al relativo StandardOutput flusso.When asynchronous read operations start, the event handler is called each time the associated Process writes a line of text to its StandardOutput stream.

È possibile annullare un'operazione di lettura asincrona chiamando CancelOutputRead.You can cancel an asynchronous read operation by calling CancelOutputRead. L'operazione di lettura può essere annullata dal chiamante o dal gestore dell'evento.The read operation can be canceled by the caller or by the event handler. Dopo l'annullamento, è possibile chiamare BeginOutputReadLine per riprendere le operazioni di lettura asincrone.After canceling, you can call BeginOutputReadLine again to resume asynchronous read operations.

Nota

È possibile combinare le operazioni di lettura sincrone e asincrone su un flusso reindirizzato.You cannot mix asynchronous and synchronous read operations on a redirected stream. Una volta reindirizzato di un' Process viene aperto in modalità asincrona o sincrona, tutte le successive lettura operazioni su tale flusso devono essere la stessa modalità.Once the redirected stream of a Process is opened in either asynchronous or synchronous mode, all further read operations on that stream must be in the same mode. Ad esempio, non seguire BeginOutputReadLine con una chiamata a ReadLine nel StandardOutput flusso, o viceversa.For example, do not follow BeginOutputReadLine with a call to ReadLine on the StandardOutput stream, or vice versa. Tuttavia, è possibile leggere due flussi diversi in modi diversi.However, you can read two different streams in different modes. Ad esempio, è possibile chiamare BeginOutputReadLine e quindi chiamare ReadLine per il StandardError flusso.For example, you can call BeginOutputReadLine and then call ReadLine for the StandardError stream.

Sicurezza

LinkDemand
per un'attendibilità totale per il chiamante immediato.for full trust for the immediate caller. Impossibile utilizzare questo membro in codice parzialmente attendibile.This member cannot be used by partially trusted code.

Si applica a

Vedi anche