Why does StandardOutput.Read() block when StartInfo.RedirectStandardInput is set to true?

i fought and fought with this just last week actually… for some reason anything other than the Read() call (ReadToEnd() was not what i needed) seemed to block and never return. here’s what i did to finally get it to “work”:

snip 1:

    private bool ThreadExited = true;
    private bool ExitThread = false;
    private void ReadThread()
    {
        while (!ExitThread)
        {
            string Output = "";

            int CharacterInt = myProcess.StandardOutput.Read();

            while (CharacterInt > 0)
            {
                char Character = (char)CharacterInt;
                Output += Character;

                var MyDelegate = new delegateUpdateText(UpdateText);
                Invoke(MyDelegate, Output);

                Output = "";
                CharacterInt = myProcess.StandardOutput.Read();
            }

            System.Threading.Thread.Yield();
        }

        ThreadExited = true;
    }

snip 2:

    private void InitializeProcess()
    {
        ThreadExited = true;
        ExitThread = true;

        while (!ThreadExited)
            System.Threading.Thread.Sleep(1000);

        ThreadExited = false;
        ExitThread = false;

        myProcess = new Process();

        ProcessStartInfo PSI = myProcess.StartInfo;

        PSI.FileName = @"cmd.exe";
        PSI.UseShellExecute = false;
        PSI.RedirectStandardError = false;
        PSI.RedirectStandardInput = true;
        PSI.RedirectStandardOutput = true;
        PSI.CreateNoWindow = false;
        PSI.ErrorDialog = true;


        myProcess.StartInfo = PSI;

        myProcess.Exited += new EventHandler(myProcess_Exited);

        myProcess.EnableRaisingEvents = false;


        myProcess.Start();

        ReadThreadThread = new System.Threading.Thread(ReadThread);
        ReadThreadThread.Start();
    }
    private System.Threading.Thread ReadThreadThread;

that finally ended up working for me. in my case i was writing text to to a textbox but that should be easy enough to modify to something else. but anything else i did caused issues due to the blocks; for some reason even if i used reflection to get the number of bytes that were available, calling the ReadBlock() function would block. never did figure it out to my satisfaction.

Leave a Comment