https://msdn.microsoft.com/zh-cn/library/azure/system.diagnostics.datareceivedeventhandler
创建 DataReceivedEventHandler 委托时,需要标识将处理该事件的方法。 若要将事件与事件处理程序关联,请将该委托的一个实例添加到事件中。 除非移除了该委托,否则每当发生该事件时就会调用事件处理程序。 有关事件处理程序委托的更多信息,请参见处理和引发事件。
若要以异步方式收集的重定向 StandardOutput 或 StandardError 流输出的一个过程中,添加事件处理程序 OutputDataReceived 或ErrorDataReceived 事件。 每次该过程将一行写入相应的重定向流时,会引发这些事件。 当关闭重定向的流时,null 的行发送到事件处理程序。确保在访问前事件处理程序检查此条件 Data 属性。 例如,您可以使用 static 方法 String.IsNullOrEmpty 验证 Data 事件处理程序中的属性。
下面的代码示例演示如何执行异步读取的操作的重定向 StandardOutput 流 排序 命令。 排序 命令是一个控制台应用程序,读取对文本输入进行排序。
此示例将创建 DataReceivedEventHandler 委托 SortOutputHandler 事件处理程序,并将关联委托,它具有 OutputDataReceived 事件。 事件处理程序收到文本行的重定向 StandardOutput 流中,格式化文本,并将文本写入到屏幕。
// 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. outLine.Data即为输出的信息(string类型) if (!String.IsNullOrEmpty(outLine.Data)){numOutputLines++;// Add the text to the collected output.sortOutput.Append(Environment.NewLine + "[" + numOutputLines.ToString() + "] - " + 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.ToString());}}} }
DataReceivedEventArgs.Data 屬性
https://msdn.microsoft.com/zh-tw/library/system.diagnostics.datareceivedeventargs.data(v=vs.110).aspx
public string Data { get; }
屬性值
Type: System.String已寫入的那一行透過關聯 Process 至其重新導向 StandardOutput 或 StandardError 資料流。
當您重新導向 StandardOutput 或 StandardError 的資料流 Process 對事件處理常式中,是每次引發事件的處理程序會寫入重新導向資料流中的一條線。 Data 屬性是一行, Process 寫入重新導向的輸出資料流。 事件處理常式可以使用 Data 屬性來篩選程序的輸出,或將輸出寫入至替代位置。例如,您可以建立將所有錯誤輸出行都儲存到指定的錯誤記錄檔的事件處理常式。
行的定義是一串字元後面接著換行字元 ("\n") 或歸位字元後面緊跟著一條線摘要 ("\r\n")。 行的字元是使用預設系統 ANSI 字碼頁來編碼。 Data 屬性不含結束歸位字元或換行字元。
當重新導向資料流已關閉時,null 的列會傳送至事件處理常式。 請確定您的事件處理常式會檢查 Data 屬性,適當地才能存取它。 例如,您可以使用靜態方法 String.IsNullOrEmpty 驗證 Data 事件處理常式中的屬性。
下列程式碼範例將說明簡單的事件處理常式相關聯 OutputDataReceived 事件。 事件處理常式收到文字行的重新導向 StandardOutput 格式化的文字,並將文字寫入至螢幕的資料流。
using System; using System.IO; using System.Diagnostics; using System.Text;class StandardAsyncOutputExample {private static int lineCount = 0;private static StringBuilder output = new StringBuilder();public static void Main(){Process process = new Process();process.StartInfo.FileName = "ipconfig.exe";process.StartInfo.UseShellExecute = false;process.StartInfo.RedirectStandardOutput = true;process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>{// Prepend line numbers to each line of the output.if (!String.IsNullOrEmpty(e.Data)){lineCount++;output.Append("\n[" + lineCount + "]: " + e.Data);}});process.Start();// Asynchronously read the standard output of the spawned process. // This raises OutputDataReceived events for each line of output.process.BeginOutputReadLine();process.WaitForExit();// Write the redirected output to this application's window.Console.WriteLine(output);process.WaitForExit();process.Close();Console.WriteLine("\n\nPress any key to exit.");Console.ReadLine();} }
DataReceivedEventArgs 類別
https://msdn.microsoft.com/zh-tw/library/system.diagnostics.datareceivedeventargs(v=vs.110).aspx
名稱 | 描述 | |
---|---|---|
Equals(Object) | 判斷指定的物件是否等於目前的物件。(繼承自 Object。) | |
Finalize() | 在記憶體回收開始前,允許物件嘗試釋放資源,並執行其他清除作業。(繼承自 Object。) | |
GetHashCode() | 做為預設雜湊函式。(繼承自 Object。) | |
GetType() | 取得目前執行個體的 Type。(繼承自 Object。) | |
MemberwiseClone() | 建立目前 Object 的淺層複製。(繼承自 Object。) | |
ToString() | 傳回代表目前物件的字串。(繼承自 Object。) |
To asynchronously collect the redirected P:System.Diagnostics.Process.StandardOutput or P:System.Diagnostics.Process.StandardError stream output of a process, you must create a method that handles the redirected stream output events. The event-handler method is called when the process writes to the redirected stream. The event delegate calls your event handler with an instance of T:System.Diagnostics.DataReceivedEventArgs. The P:System.Diagnostics.DataReceivedEventArgs.Data property contains the text line that the process wrote to the redirected stream.
The following code example illustrates how to perform asynchronous read operations on the redirected P:System.Diagnostics.Process.StandardOutput stream of the sort command. The sort command is a console application that reads and sorts text input.
The example creates an event delegate for the SortOutputHandler event handler and associates it with the E:System.Diagnostics.Process.OutputDataReceived event. The event handler receives text lines from the redirected P:System.Diagnostics.Process.StandardOutput stream, formats the text, and writes the text to the screen.
// 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);}}} }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.ToString());}}} }