c#GUI在启动控制台应用程序后冻结

c#GUI在启动控制台应用程序后冻结,c#,C#,我制作了一个运行ping并在文本字段中显示结果的应用程序。当我单击start ping按钮时,GUI挂起,文本字段没有输出任何内容。这个GUI挂起的原因是可以理解的,GUI正在等待控制台应用程序完成。我不明白如何在控制台应用程序的文本字段中实现输出 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using S

我制作了一个运行ping并在文本字段中显示结果的应用程序。当我单击start ping按钮时,GUI挂起,文本字段没有输出任何内容。这个GUI挂起的原因是可以理解的,GUI正在等待控制台应用程序完成。我不明白如何在控制台应用程序的文本字段中实现输出

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1 ping = new Class1();
            ping.startPing();
            string output = ping.output();
            richTextBox1.AppendText(output + "\n");
            richTextBox1.Update();
        }

        static private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }

    class Class1
    {
        private Process p = new Process();

        public void startPing()
        {
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "c:/windows/system32/ping";
            p.StartInfo.Arguments = "8.8.8.8 -t";
            p.Start();
        }

        public string output()
        {
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            return output;
        }
    }
}

此代码将用于解析您的查询

  private void button1_Click(object sender, EventArgs e)
  {
          var worker = new BackgroundWorker();
          worker.DoWork += (o, ea) =>
          {
                Class1 ping = new Class1();
                ping.startPing();
                string output = ping.output();
                richTextBox1.AppendText(output + "\n");
                richTextBox1.Update();

          };
          worker.RunWorkerCompleted += (o, ea) =>
          {
                //You will get pointer when this worker finished the job.
          };
          worker.RunWorkerAsync();
    }

使用源代码实现后,如果有任何问题,请告诉我。

GUI会冻结,因为您在与GUI相同的线程上运行ping,从而阻止它更新,直到您的操作完成,您可能希望启动一个新的线程或后台工作程序,并在其上运行ping,您认为如何
p.WaitForExit()是什么?文件是否建议了替代方法?还有很多例子是关于使用
p.Exited
事件(不要忘记允许它-
p.EnableRaisingEvents=true;
)将结果从控制台拉入Try的c#可能的副本,然后删除
p.WaitForExit()仅仅发布代码并不能帮助OP理解解决方案。请随代码一起提供解释。