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#
VB
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 格式化的文字,並將文字寫入至螢幕的資料流。

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

語法
C#
C++
F#
VB
public class DataReceivedEventArgs : EventArgs

屬性
 名稱描述
System_CAPS_pubpropertyData

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

方法
 名稱描述
System_CAPS_pubmethodEquals(Object)

判斷指定的物件是否等於目前的物件。(繼承自 Object。)

System_CAPS_protmethodFinalize()

在記憶體回收開始前,允許物件嘗試釋放資源,並執行其他清除作業。(繼承自 Object。)

System_CAPS_pubmethodGetHashCode()

做為預設雜湊函式。(繼承自 Object。)

System_CAPS_pubmethodGetType()

取得目前執行個體的 Type。(繼承自 Object。)

System_CAPS_protmethodMemberwiseClone()

建立目前 Object 的淺層複製。(繼承自 Object。)

System_CAPS_pubmethodToString()

傳回代表目前物件的字串。(繼承自 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());}}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/458450.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

coreData

CoreData使用 创建步骤流程 第一步先创建.xcdatamodeld文件&#xff08;New File -> iOS -> Core Data ->Data Model&#xff09; 屏幕快照 2016-07-07 下午10.40.16.png名字虽然可以任意取&#xff0c;但最好还是取和自己存储数据库名字一样的名字。这样可读性更高些…

命令行下mysql新建用户及分配权限

创建用户&#xff1a; CREATE USER usernamehost IDENTIFIED BY password; 说明:username – 你将创建的用户名, host – 指定该用户在哪个主机上可以登陆,如果是本地用户可用localhost, 如 果想让该用户可以从任意远程主机登陆,可以使用通配符%. password – 该用户的登陆密…

PetaPoco初体验(转)

PetaPoco初体验&#xff08;转&#xff09; PetaPoco初体验&#xff08;转&#xff09;大部分转自&#xff1a; http://landyer.com/archives/138 PetaPoco C#微型ORM框架&#xff0c;基本无需配置&#xff0c;仅由单个cs文件构成&#xff0c;支持.net3.5 .net4.0。 截稿时Peta…

iOS当中的设计模式

代理模式 应用场景&#xff1a;当一个类的某些功能需要由别的类来实现&#xff0c;但是又不确定具体会是哪个类实现。 优势&#xff1a;解耦合 敏捷原则&#xff1a;开放-封闭原则 实例&#xff1a;tableview的 数据源delegate&#xff0c;通过和protocol的配合&#xff0c…

c#的dllimport使用方法详解

DllImport是System.Runtime.InteropServices命名空间下的一个属性类&#xff0c;其功能是提供从非托管DLL&#xff08;托管/非托管是微软的.net framework中特有的概念&#xff0c;其中&#xff0c;非托管代码也叫本地&#xff08;native&#xff09;代码。与Java中的机制类似&…

each函数循环数据表示列举,列举循环的时候添加dom的方法

var dotBox $(#bannerNum);var item <li></li>;var itemSize $(#bannerBack p).length;var dotBoxWidth itemSize*24;$(#bannerBack p).each(function () { dotBox.append(<li></li>); dotBox.find(li).eq(0).addClass(current);});这里要根…

使用lxml代替beautifulsoup

深入使用过lxml的都会深深地喜欢上它,虽然BeautifulSoup很流行,但是深入了解lxml后,你就再也不会使用bs了 我觉得beautifulsoup不好用,速度也慢(虽然可以使用lxml作为解析器了).另外soup.find_all这种简直就是手工时代的操作(很多人使用find find_all这几个函数, 其实它们使用起…

QT调用dll且进入DLL src code调试

qt应用程序AA.exe调用qt写的BB.DLL时&#xff0c;进入BB.DLL src code调试 1、debug生成AA.exe 2、将debug生成的AA.exe整包debug folder放到BB.dll的debug生成的文件夹中 3、设置BB.dll这个project&#xff1a;项目----运行-----Executable中选择BB.dll的debug文件夹中的AA.ex…

php安装编译时 configure: error: Cannot find OpenSSL's evp.h

yum install error: protected multilib versions errorsudo yum downgrade openssl 降级sudo yum install openssl-devel 另外参考yum install -y ncurses-devel yum install openssl openssl-develyum install openssl openssl-devel --setoptprotected_multilibfalse ln -s …

laravel项目中css样式表的背景图片不显示

刚学laravel&#xff0c;遇到了很多坑&#xff0c;感觉laravel是挺强大的。 建好后台项目&#xff0c;奈何css样式表的背景图片不显示 .mainhd {background: url(../images/sky/body_bg.png) repeat-x 0px 0px; } 按理上面的写法没错&#xff0c;因为是从别的后台搬过来的&…

KVC KVO

1、KVC&#xff0c;即是指 NSKeyValueCoding&#xff0c;一个非正式的Protocol&#xff0c;提供一种机制来间接访问对象的属性。而不是通过调用Setter、Getter方法访问。KVO 就是基于 KVC 实现的关键技术之一。 Demo&#xff1a; interface myPerson : NSObject { …

VS2010中 C++创建DLL图解

一、DLL的创建 创建项目: Win32->Win32项目&#xff0c;名称&#xff1a;MyDLL 选择DLL (D) ->完成. 1、新建头文件testdll.htestdll.h代码如下&#xff1a;#ifndef TestDll_H_#define TestDll_H_#ifdef MYLIBDLL#define MYLIBDLL extern "C" _declspec(dllimp…

js理解 call( ) | apply( ) | caller( ) | callee( )

被js的这几个方法搞的this晕头转向&#xff0c;下定决心搞清楚&#xff1b;1、call( )和apply( ):两者都可以将函数绑定到另外一个对象上去运行&#xff0c;只是参数的传递方式不同&#xff0c;两者都可以使当前函数拥有另一个对象的属性和方法&#xff0c;实现js下的继承&…

上传SVN丢失.a文件的问题

iOS项目上传到svn中&#xff0c;.a文件丢失 用Cornerstone工具&#xff0c;解决这个问题 1.打开Cornerstone左上角&#xff0c;点Cornerstone->Preferences->Subversion 2.Global lgnores下面有一个Use default global ignores 默认这里方框中会打钩&#xff08;这就是.a…

使用公用表表达式的递归查询

微软从SQL2005起引入了CTE(Common Table Expression)以强化T-SQL。公用表表达式 (CTE) 具有一个重要的长处&#xff0c;那就是可以引用其自身。从而创建递归 CTE。递归 CTE 是一个反复运行初始 CTE 以返回数据子集直到获取完整结果集的公用表表达式。 当某个查询引用递归 CTE 时…

C#委托实现C++ Dll中的回调函数

from:https://blog.csdn.net/ferrycooper/article/details/63261771很多的Dll都是C和C写的&#xff0c;那么如果C#想要调用Dll中的函数怎么办&#xff0c;尤其是Dll函数其中一个参数是函数指针的&#xff0c;即里面有回掉函数的用C#怎么实现&#xff1f; C中的回掉函数在C#中有…

安装Birt方法

安装BIRT 方法&#xff1a; 博客地址&#xff1a;http://www.mamicode.com/info-detail-850588.html 注意&#xff1a;在 Install new Software 中输入地址&#xff1a;http://download.eclipse.org/birt/update-site/4.2-interim 看好了 出来的四项要全部选中 &#xff0c;然后…

iOS NSString和NSDate转换

后台返回的时间字符串不是标准的时间而是计算机时间的时候&#xff0c;我们需要将它们转换为标准时间&#xff0c;再进行转换。 //字符串转为时间&#xff0c;时间格式自己定 NSString * time "1501776000"; //时间字符串 NSInteger num [time integerValue]; …

15个最好的HTML5前端响应式框架(2014)

文中的多个框架基于SASS创建&#xff0c;SCSS是一种比LESS更简洁的样式表编程语言&#xff0c;它能够编绎成CSS&#xff0c;可复用CSS代码&#xff0c;声明变量&#xff0c;甚至是函数&#xff0c;类Ruby/Python的语法。參见&#xff1a; LESS vs SASS&#xff1f;选择哪种CSS样…

DLL导出类和导出函数

from:https://blog.csdn.net/goodluckmt/article/details/526912971、动态库DLL中的类或者函数有时候要被其他的库调用&#xff0c;因此需要被其他库调用的类或者函数需要进行导出。 2、首先编写需要导出的DLL&#xff0c;新建一个工程设置应用程序类型为DLL3、类的代码如下 头…