DataReceivedEventHandler 代理人

定義

表示將處理 OutputDataReceivedErrorDataReceived 事件或 Process 事件的方法。

public delegate void DataReceivedEventHandler(System::Object ^ sender, DataReceivedEventArgs ^ e);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
type DataReceivedEventHandler = delegate of obj * DataReceivedEventArgs -> unit
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)

參數

sender
Object

事件的來源。

e
DataReceivedEventArgs

DataReceivedEventArgs,其中包含事件資料。

範例

下列程式碼範例說明如何在排序命令的重新 StandardOutput 導向資料流程上執行非同步讀取作業。 排序命令是可讀取和排序文字輸入的主控台應用程式。

此範例會 DataReceivedEventHandler 建立事件處理常式的 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

備註

建立 DataReceivedEventHandler 委派時,必須識別處理事件的方法。 若要使事件與您的事件處理常式產生關聯,請將委派的執行個體 (Instance) 加入至事件。 除非您移除委派,否則每當事件發生時就會呼叫事件處理常式。 如需事件處理常式委派的詳細資訊,請參閱 處理和引發事件

若要以非同步方式收集進程的重新導向 StandardOutputStandardError 資料流程輸出,請將事件處理常式新增至 OutputDataReceivedErrorDataReceived 事件。 每次進程將一行寫入對應的重新導向資料流程時,都會引發這些事件。 當重新導向資料流程關閉時,會將 Null 行傳送至事件處理常式。 在存取 Data 屬性之前,請確定事件處理常式會檢查此條件。 例如,您可以使用 static 方法來 String.IsNullOrEmpty 驗證 Data 事件處理常式中的 屬性。

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。

適用於

另請參閱