繁体   English   中英

我如何阅读Process.StandardOutput属性异步?

[英]How do I read Process.StandardOutput Property async?

我目前正在尝试读取CMD文件的内容,并且该文件正在运行,但是在cmd关闭之前,它不会将文本附加到文本框中。 该.BAT文件用于启动和管理服务器,因此cmd内容将不断更新。 如果我关闭cmd文件,它将关闭服务器,但我们不希望这样做,因为那样很好,服务器需要运行。 这是两难选择。

在cmd关闭之前,不会将文本附加到文本框。

我尝试将其放在后台工作器中并异步运行,但它却做同样的事情。 我如何阅读过程? StandardOutput属性异步,所以我不会陷入僵局?

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using System.IO;

namespace SendInput
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        StreamReader outputReader = null;
        StreamReader errorReader = null;

        private void btnCommand_Click(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;

            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //Create Process Start information
                ProcessStartInfo processStartInfo =
                    new ProcessStartInfo(@"C:\Users\devPC\Desktop\Server\run.bat");
                processStartInfo.ErrorDialog = false;
                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;

                //Execute the process
                Process process = new Process();
                process.StartInfo = processStartInfo;
                bool processStarted = process.Start();
                if (processStarted)
                {
                    //Get the output stream
                    outputReader = process.StandardOutput;
                    errorReader = process.StandardError;

                    //Display the result
                    string displayText = "Output \n==============\n";
                    displayText += outputReader.ReadToEnd();
                    displayText += "\nError\n==============\n";
                    displayText += errorReader.ReadToEnd();
                    rtbConsole.Text = displayText;
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

这使用async / await启动进程,然后使用进程输出事件更新UI。

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using System.IO;

namespace SendInput
{
    public partial class Form1: Form
    {
        private SynchronizationContext _syncContext;

        public Form1()
        {
            InitializeComponent();
        }

        private async void btnCommand_Click(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;

            await StartProcessAsync();
        }

        private Task StartProcessAsync()
        {
            return Task.Run(()=>
            {
                try
                {
                    //Create Process Start information
                    ProcessStartInfo processStartInfo =
                        new ProcessStartInfo(@"C:\Users\devPC\Desktop\Server\run.bat");
                    processStartInfo.ErrorDialog = false;
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.RedirectStandardError = true;
                    processStartInfo.RedirectStandardInput = true;
                    processStartInfo.RedirectStandardOutput = true;

                    //Execute the process
                    Process process = new Process();
                    process.StartInfo = processStartInfo;

                    process.OutputDataReceived += (sender, args) => UpdateText(args.Data);
                    process.ErrorDataReceived += (sender, args) => UpdateErrorText(args.Data);

                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit(); 
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });
        }

        private void UpdateText(string outputText)
        {
            _syncContext.Post(x => rtbConsole.AppendText("Output \n==============\n"), null);                
            _syncContext.Post(x => rtbConsole.AppendText(outputText), null);
        }

        private void UpdateErrorText(string outputErrorText)
        {
            _syncContext.Post(x => rtbConsole.AppendText("\nError\n==============\n"), null);
            _syncContext.Post(x => rtbConsole.AppendText(outputErrorText), null);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM