Process.BeginOutputReadLine メソッドとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > Process.BeginOutputReadLine メソッドの意味・解説 

Process.BeginOutputReadLine メソッド

メモ : このメソッドは、.NET Framework version 2.0新しく追加されたものです。

アプリケーションリダイレクトされた StandardOutput ストリームで、非同期読み取り操作開始します

名前空間: System.Diagnostics
アセンブリ: System (system.dll 内)
構文構文

<ComVisibleAttribute(False)> _
Public Sub BeginOutputReadLine
Dim instance As Process

instance.BeginOutputReadLine
[ComVisibleAttribute(false)] 
public void BeginOutputReadLine ()
[ComVisibleAttribute(false)] 
public:
void BeginOutputReadLine ()
/** @attribute ComVisibleAttribute(false) */ 
public void BeginOutputReadLine ()
ComVisibleAttribute(false) 
public function BeginOutputReadLine ()
例外例外
例外種類条件

InvalidOperationException

ProcessStartInfo.RedirectStandardOutput プロパティfalse です。

または

非同期読み取り操作は、既に StandardOutput ストリーム実行中です。

または

StandardOutput ストリームは、非同期読み取り操作によって使用されています。

解説解説

StandardOutput ストリーム読み取りは、同期または非同期実行できますReadReadLine、および ReadToEnd のようなメソッドは、プロセス出力ストリーム同期読み取り操作実行します。これらの同期読み取り操作は、関連する Process がその StandardOutput ストリーム書き込むか、ストリーム閉じるまで完了しません。

対照的にBeginOutputReadLineStandardOutput ストリーム非同期読み取り操作開始します。このメソッドは、ストリーム出力指定されイベント ハンドラ有効にした後、直ち呼び出し元に制御返します。これにより、呼び出し元は、ストリーム出力イベント ハンドラリダイレクトされている間に他の作業実行できます

次の手順従いProcessStandardOutput非同期読み取り操作実行してください

  1. UseShellExecute を false設定します

  2. RedirectStandardOutputtrue設定します

  3. OutputDataReceived イベントイベント ハンドラ追加しますイベント ハンドラは、System.Diagnostics.DataReceivedEventHandler デリゲート シグネチャ一致する必要があります

  4. Process開始します

  5. ProcessBeginOutputReadLine呼び出します。この呼び出しにより、非同期読み取り操作StandardOutput開始されます。

非同期読み取り操作開始されると、関連付けられた Processテキストの行を StandardOutput ストリーム書き込むたびにイベント ハンドラ呼び出されます。

非同期読み取り操作キャンセルするには、CancelOutputRead を呼び出します。読み取り操作は、呼び出し元またはイベント ハンドラによってキャンセルできますキャンセル後に非同期読み取り操作再開するには、BeginOutputReadLine再度呼び出します。

メモメモ

リダイレクトされたストリームで、非同期読み取り操作同期読み取り操作混在させることはできません。Processリダイレクトされたストリーム非同期モードまたは同期モード開いた後は、それ以降、そのストリーム対すすべての読み取り操作は同じモードで行う必要があります。たとえば、StandardOutputBeginOutputReadLine の後に ReadLine呼び出し続けないください。逆も同様です。ただし、2 つ異なストリームそれぞれ別のモード読み取ることはできます。たとえば、BeginOutputReadLine呼び出した後でStandardError ストリーム用に ReadLine呼び出すことができます

使用例使用例

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

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

' 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 = {0} sorted text
 line(s) ", _
                              numOutputLines)
            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.ToString() + "] - "
 _
                         + outLine.Data)
         End If
      End Sub 
   End Class  
End Namespace 
// 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;
            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 += new 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);
                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.ToString() + "] - "
 + outLine.Data);
            }
        }
    }
}
// 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 );
      }
   }
};
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Process クラス
Process メンバ
System.Diagnostics 名前空間
ProcessStartInfo.RedirectStandardOutput
StandardOutput
OutputDataReceived
DataReceivedEventHandler デリゲート
CancelOutputRead


このページでは「.NET Framework クラス ライブラリ リファレンス」からProcess.BeginOutputReadLine メソッドを検索した結果を表示しています。
Weblioに収録されているすべての辞書からProcess.BeginOutputReadLine メソッドを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からProcess.BeginOutputReadLine メソッドを検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Process.BeginOutputReadLine メソッド」の関連用語

Process.BeginOutputReadLine メソッドのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Process.BeginOutputReadLine メソッドのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS