【问题标题】:Read external console app window读取外部控制台应用程序窗口
【发布时间】:2011-02-14 19:40:50
【问题描述】:

我正在调用一个不断向控制台窗口输出信息的外部命令行应用程序。我想阅读这些信息并将其传递到我的代码中以报告进度。

但是...我从来没有得到任何回报。如果我使用 sr.ReadToEnd(),它会一直卡住,直到应用程序关闭并且返回一个空字符串。我需要做什么才能正确读取外部应用程序命令行窗口中的文本?

这是我的测试代码,不需要线程化,无论我做什么,流都会返回空:

    private void runApp(string args, string app)
    {
        ProcessStartInfo pInfo = new ProcessStartInfo(app, args);
        pInfo.CreateNoWindow = true;
        pInfo.RedirectStandardOutput = true;
        pInfo.UseShellExecute = false;

        Thread t = new Thread(getProgress);
        t.Start();

        p = Process.Start(pInfo);
        p.WaitForExit();
        p.Close();
    }
    private void getProgress()
    {
        StreamReader sr = p.StandardOutput;

        //Get's stuck here until the app closes, nothing is ever outputted
        string output = sr.ReadLine();

        //Just for testing, debugging here
        while (true)
        {
            Console.WriteLine(output);
            System.Threading.Thread.Sleep(1000);
        }
        sr.Close();
    }

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    我认为线程是在进程之前启动的,并且不知何故你陷入了僵局。查看http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

    【讨论】:

    • 即使不使用上面的线程,我也得到了类似的结果。然而,这整个代码在一个线程内运行。让我把这段代码放在一个没有多线程确认的干净的测试应用程序中。
    • 你是对的。这是一个线程问题。不在线程内运行时可以正常工作。
    【解决方案2】:

    我看到这个主题每隔几天就会被一次又一次地问到......在这里查看我的答案:

    Running a c++ console app inside a C# console app

    【讨论】:

    • 使用您的代码,我被困在这一行:“while ((str = sOut.ReadLine()) != null && !sOut.EndOfStream)”。即使在外部应用程序关闭后,我的代码也不会前进。
    • 正如 Richard 所指出的,是由线程问题引起的。谢谢。提高您的答案以添加一种阅读应用输出的好方法。
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2011-04-20
    • 2014-02-17
    • 1970-01-01
    • 2022-08-22
    相关资源
    最近更新 更多