0

I am calling an external command line app that continously spits out information into the console window. I'd like to read the information and pass it into my code in order to report progress.

But... I never get any values back at all. If I use sr.ReadToEnd(), it gets stuck until the app closes and just an empty string comes back. What do I need to do to read the text in the command line window of the external app correctly?

Here is my code for the test, doesn't have to be threaded, the stream comes back empty no matter what I seem to do:

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

2 Answers 2

1

I'm thinking that the thread is started before the process and somehow you are deadlocking. Check out http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

Sign up to request clarification or add additional context in comments.

2 Comments

I got similar results even when not using the thread above. This entire code is running inside of a thread however. Let me put this code inside of a clean test app without multi-threading to confirm.
You're right. It's a threading issue. Got it working when not running inside a thread.
1

I see this subject is asked again and again every few days... see my answer here:

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

2 Comments

With your code, I get stuck at this line: "while ((str = sOut.ReadLine()) != null && !sOut.EndOfStream)". Even after the external app closes down, my code never advances.
Was caused by a threading issue as Richard noted. Thanks. Upping your answer for adding a good way to read the app output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.