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

屬性
  名稱 描述
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 委托 接收调用执行进程返回数据相关推荐

  1. spring返回数据使用ajax,【spring 后台跳转前台】使用ajax访问的后台,后台正常执行,返回数据,但是不能进入前台的ajax回调函数中...

    问题1: 使用ajax访问的后台,后台正常执行,并且正常返回数据,但是不能进入前台的ajax回调函数中 问题展示: 问题解决: 最后发现是因为后台的方法并未加注解:@ResponseBody,导致方法 ...

  2. jQuery:ajax调用成功后返回数据

    本文翻译自:jQuery: Return data after ajax call success [duplicate] This question already has answers here ...

  3. java接收流文件并返回数据

    java接收流文件并返回数据 @RequestMapping(value="/updateStatus") public Object updateStatus(HttpServl ...

  4. rpa调用https接口 返回数据异常_金融企业“银行余额RPA查询机器人”解读

    一.财务机器人应用背景 公司简介 金融行业银行卡联合组织--是只通过银联跨行交易清算系统,实现商业银行系统间的互联互通和资源共享,保证银行卡跨行.跨地区和跨境的使用的组织. 总部设于上海,作为中国的银 ...

  5. ajax获取的数据中包含html代码,执行ajax返回数据中包含的script脚本代码

    ajax虽然很方便,提升了我们的交互体验,但是它也有可恨之处,就是ajax请求得到的数据中如果包含脚本代码,比如说请求得到的是一块html内容,我们把这块html内容插入到网页中的某个地方,但是其中明 ...

  6. Java调用MySQL并返回数据_Java调用MySQL存储过程并获得返回值的方法

    本文实例讲述了Java调用MysqL存储过程并获得返回值的方法.分享给大家供大家参考.具体如下: private void empsInDept(Connection myConnect,int de ...

  7. android 调用app后返回数据,h5和app交互

    1.h5调用app的方法或者传值 // Android: window.Android.方法名(参数) // ios window.webkit.messageHandlers.方法名.postMes ...

  8. 通过Feign调用接口,返回数据时出现数据乱码

    在路径映射上添加 produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = "application/json;charset ...

  9. 【Android 逆向】Android 进程注入工具开发 ( 注入代码分析 | 远程调用 目标进程中 libc.so 动态库中的 mmap 函数 三 | 等待远程函数执行完毕 | 寄存器获取返回值 )

    文章目录 前言 一.等待远程进程 mmap 函数执行完毕 二.从寄存器中获取进程返回值 三.博客资源 前言 前置博客 : [Android 逆向]Android 进程注入工具开发 ( 注入代码分析 | ...

最新文章

  1. requireJS的基本使用
  2. Java设计模式(十四):MVC设计模式
  3. C++子类父类成员函数的覆盖和隐藏实例详解
  4. 全参考客观视频质量评价方法 (MSE, PSNR,SSIM)原理
  5. print (re.findall((?:abc)+,abcabcabc))
  6. 《精通ArcGIS Server 应用与开发》——2.4 ArcGIS Server的安装与配置
  7. Java课程设计-基于Swing的文本编辑器
  8. LCD12864 液晶显示-汉字及自定义显示(并口)
  9. SD卡驱动(详细介绍,不明白的人可以仔细看看了.有流程图)
  10. vue实现li列表的新增删除和修改
  11. SKYPE的BUG 7/8
  12. activemq-messages-dequeud-but-not-consumed
  13. 前大灯是近光灯还是远光灯_大灯是近光灯还是远光灯
  14. 用mysql查询图书的信息_PHP+MySQL 利用mysql_fetch_row模糊查询图书信息
  15. Matlab幂律变换及直方图均衡化
  16. 分布式数据库架构--分库、分表、排序、分页、分组、实现
  17. 简单五步设置群晖NAS绑定自有域名实现外网访问
  18. BLOCK层代码分析(9)IO下发之IO下发
  19. 硬核知识大全 作为程序员你不得不了解
  20. 云栖大会人脸识别闸机【技术亮点篇7】--人脸识别闸机采用

热门文章

  1. 解决报错 javax.persistence.TransactionRequiredException: Executing an update/delete query
  2. Maven 添加本地 jar 包、添加依赖 jar 文件到本地 Maven 仓库、引用本地 jar
  3. equals和==的区别(转)
  4. 线程----BlockingQueue
  5. 一个立即关闭显示器的小软件(Masm开发,只有3KB大小)
  6. MediaWiki安装配置(Linux)【转】
  7. PIX525故障一例,求解
  8. touchesEnded不响应
  9. Frequent Pattern 挖掘之二(FP Growth算法)(转)
  10. VIP - virtual IP address