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

// 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

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.

// 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());
            }
        }
    }
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
可以使用C#编写一个可执行程序,被其它程序调用返回数据的过程可以通过控制台输出来实现。具体步骤如下: 1. 创建一个新的控制台应用程序项目。 2. 编写程序的核心逻辑,即实现其它程序需要调用的功能。 3. 在程序中使用 Console.WriteLine() 方法输出需要返回数据。 4. 编译并生成可执行文件。 5. 在其它程序中使用 Process.Start() 方法启动该可执行程序,并使用 Process.StandardOutput.ReadToEnd() 方法获取其输出数据。 下面是一个简单示例,假设我们需要编写一个程序,能够计算两个整数的和,并返回结果: ```csharp using System; namespace Adder { class Program { static void Main(string[] args) { if (args.Length == 2) { int a = int.Parse(args[0]); int b = int.Parse(args[1]); int sum = a + b; Console.WriteLine(sum); } } } } ``` 编译并生成可执行文件后,我们可以在其它程序中使用以下代码来调用该程序并获取输出数据: ```csharp using System.Diagnostics; namespace Caller { class Program { static void Main(string[] args) { Process process = new Process(); process.StartInfo.FileName = "Adder.exe"; process.StartInfo.Arguments = "2 3"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); Console.WriteLine("Sum: " + output); } } } ``` 在这个示例中,我们启动了 Adder.exe 程序,并传递了两个整数参数 2 和 3。程序会计算它们的和,并将结果输出到控制台。我们在调用程序时使用了 RedirectStandardOutput 属性来指定输出数据需要通过 StandardOutput 属性获取,这样我们就可以获取程序输出的数据并在调用程序的程序中使用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值