【问题标题】:c# GUI freezes after launching console applicationc# GUI 在启动控制台应用程序后冻结
【发布时间】:2019-03-22 17:34:27
【问题描述】:

我制作了一个运行 ping 并在文本字段中显示结果的应用程序。当我单击开始 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;
        }
    }
}

【问题讨论】:

  • GUI 冻结,因为您在与 GUI 相同的线程上运行 ping,因此在您的操作完成之前阻止它更新,您可能需要考虑启动一个新线程或后台worker 并在其上运行 ping
  • 您认为p.WaitForExit(); 会做什么?文档是否建议了另一种方法? docs.microsoft.com/en-us/dotnet/api/…
  • 也有很多从控制台拉取结果到c#的例子
  • 尝试使用p.Exited 事件(不要忘记允许它-p.EnableRaisingEvents = true;)并删除p.WaitForExit();

标签: c#


【解决方案1】:

此代码将有助于解决您的查询。

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

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

【讨论】:

  • 仅仅发布代码并不能帮助 OP 理解解决方案。请提供解释以及代码。
猜你喜欢
  • 2016-03-07
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多