Process.BeginOutputReadLine 메서드

정의

애플리케이션의 리디렉션된 StandardOutput 스트림에 대해 비동기 읽기 작업을 시작합니다.

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

예외

RedirectStandardOutput 속성은 false입니다.

또는

StandardOutput 스트림에서 비동기 읽기 작업이 이미 진행 중입니다.

또는

StandardOutput 스트림이 동기적 읽기 작업에 사용되었습니다.

예제

다음 예제에서는 명령의 sort 리디렉션된 StandardOutput 스트림에서 비동기 읽기 작업을 수행하는 방법을 보여 줍니다. sort 명령 읽고 텍스트 입력을 정렬 하는 콘솔 애플리케이션입니다.

이 예제에서는 이벤트 처리기에 대한 이벤트 대리자를 SortOutputHandler 만들고 이벤트와 연결합니다 OutputDataReceived . 이벤트 처리기는 리디렉션된 StandardOutput 스트림에서 텍스트 줄을 수신하고, 텍스트의 서식을 지정하고, 텍스트를 화면에 씁니다.

// 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.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

설명

스트림은 StandardOutput 동기적으로 또는 비동기적으로 읽을 수 있습니다. Read, ReadLine, 등의 ReadToEnd 메서드는 프로세스의 출력 스트림에서 동기 읽기 작업을 수행합니다. 이러한 동기 읽기 작업은 연결된 Process 가 스트림 StandardOutput 에 쓰거나 스트림을 닫을 때까지 완료되지 않습니다.

반면, 는 BeginOutputReadLine 스트림에서 StandardOutput 비동기 읽기 작업을 시작합니다. 이 메서드는 스트림 출력에 대해 지정된 이벤트 처리기를 사용하도록 설정하고 즉시 호출자에게 반환되며, 이 호출자는 스트림 출력이 이벤트 처리기로 전달되는 동안 다른 작업을 수행할 수 있습니다.

에 대해 비동기 읽기 작업을 수행하려면 다음 단계를 수행합니다 StandardOutputProcess .

  1. UseShellExecutefalse로 설정합니다.

  2. RedirectStandardOutputtrue로 설정합니다.

  3. 이벤트에 이벤트 처리기를 추가합니다 OutputDataReceived . 이벤트 처리기는 대리자 서명과 System.Diagnostics.DataReceivedEventHandler 일치해야 합니다.

  4. Process를 시작합니다.

  5. 를 호출 BeginOutputReadLine 합니다 Process. 이 호출은 에서 StandardOutput비동기 읽기 작업을 시작합니다.

비동기 읽기 작업이 시작되면 연결된 Process 가 해당 스트림에 텍스트 StandardOutput 줄을 쓸 때마다 이벤트 처리기가 호출됩니다.

를 호출 CancelOutputRead하여 비동기 읽기 작업을 취소할 수 있습니다. 호출자 또는 이벤트 처리기에서 읽기 작업을 취소할 수 있습니다. 취소한 후 를 다시 호출 BeginOutputReadLine 하여 비동기 읽기 작업을 다시 시작할 수 있습니다.

참고

리디렉션된 스트림에서는 비동기 및 동기 읽기 작업을 혼합할 수 없습니다. 리디렉션된 스트림 Process 이 비동기 또는 동기 모드로 열리면 해당 스트림에 대한 모든 추가 읽기 작업이 동일한 모드에 있어야 합니다. 예를 들어 스트림에서 에 대한 StandardOutput 호출 ReadLine 을 따르지 BeginOutputReadLine 않거나 그 반대의 경우도 마찬가지입니다. 그러나 서로 다른 모드에서 두 개의 서로 다른 스트림을 읽을 수 있습니다. 예를 들어 를 호출 BeginOutputReadLine 한 다음 스트림을 호출 ReadLineStandardError 수 있습니다.

적용 대상

추가 정보