日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

DataReceivedEventHandler 委托 接收调用执行进程返回数据

發布時間:2023/12/20 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 DataReceivedEventHandler 委托 接收调用执行进程返回数据 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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?流中,格式化文本,并將文本寫入到屏幕。

C#C++VB// 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

語法C#C++F#VBpublic 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?格式化的文字,並將文字寫入至螢幕的資料流。

C#C++VBusing 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

語法C#C++F#VBpublic class DataReceivedEventArgs : EventArgs

屬性?名稱描述
Data

取得一行字元寫入至重新導向?Process?輸出資料流。

方法?名稱描述
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.

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

總結

以上是生活随笔為你收集整理的DataReceivedEventHandler 委托 接收调用执行进程返回数据的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。