英語で読む

次の方法で共有


DataReceivedEventHandler 代理人

定義

OutputDataReceivedErrorDataReceived イベントまたは Process イベントを処理するメソッドを表します。

C#
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);

パラメーター

sender
Object

イベントのソース。

e
DataReceivedEventArgs

イベント データを格納している DataReceivedEventArgs

次のコード例は、並べ替えコマンドのリダイレクトされたStandardOutputストリームに対して非同期読み取り操作を実行する方法を示しています。 sort コマンドは、テキスト入力を読み取って並べ替えるコンソール アプリケーションです。

この例では、 DataReceivedEventHandler イベント ハンドラーのデリゲートを SortOutputHandler 作成し、デリゲートを イベントに OutputDataReceived 関連付けます。 イベント ハンドラーは、リダイレクトされた StandardOutput ストリームからテキスト行を受け取り、テキストの書式設定を行い、テキストを画面に書き込みます。

C#
// 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);
            }
        }
    }
}

注釈

DataReceivedEventHandler デリゲートを作成する場合は、イベントを処理するメソッドを指定します。 イベント ハンドラーにイベントを関連付けるには、イベントにデリゲートのインスタンスを追加します。 イベント ハンドラーは、デリゲートを削除しない限り、イベントが発生するたびに呼び出されます。 イベント ハンドラー デリゲートの詳細については、「イベントの 処理と発生」を参照してください。

プロセスのリダイレクトされたStandardOutput出力またはStandardErrorストリーム出力を非同期的に収集するには、イベント ハンドラーを または ErrorDataReceived イベントにOutputDataReceived追加します。 これらのイベントは、プロセスが対応するリダイレクトされたストリームに行を書き込むたびに発生します。 リダイレクトされたストリームが閉じられると、null 行がイベント ハンドラーに送信されます。 プロパティにアクセスする前に、イベント ハンドラーでこの条件が Data チェックされていることを確認します。 たとえば、 メソッドString.IsNullOrEmptystatic使用して、イベント ハンドラーの プロパティをData検証できます。

拡張メソッド

GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

こちらもご覧ください