liquidcoder
liquidcoder

Reputation: 31

Is sleep is required before Process.StandardOutput.Read() method?

I'm trying create a sub-process in C# program (cmd for example) and performing read/write with process IO streams. I'm using StandardOutput.Read() method to read process output.

When I put a Thread.Sleep() method before Read(), it gives complete output but if I remove it, it displays only single line of output.

Here is the code:

string sProcess = "cmd.exe";
ProcessStartInfo psiInfo = new ProcessStartInfo();
psiInfo.FileName = sProcess;
psiInfo.CreateNoWindow = true;
psiInfo.UseShellExecute = false;
psiInfo.RedirectStandardOutput = true;
psiInfo.RedirectStandardError = true;
psiInfo.RedirectStandardInput = true;
Process pChild = new Process();
pChild.StartInfo = psiInfo;
if (pChild.Start())
{
    int ch;
    do
    {
        Thread.Sleep(50);
        ch = pChild.StandardOutput.Peek();
        if (ch > 0)
            Console.Write((char)pChild.StandardOutput.Read());
    } while (ch > 0);
    Console.WriteLine("exit");
    pChild.StandardInput.WriteLine("exit");
}

Output with Sleep enabled:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved. 

D:\ProcessDemo_001\bin\Release>exit 

Output with Sleep disabled:

Microsoft Windows [Version 6.1.7601]exit

I want to know why this happens?

Upvotes: 1

Views: 213

Answers (2)

dmaij
dmaij

Reputation: 1007

It may happen that your Peek command is executed before pChild has output text. When that happens, ch will be 0 and the while loop quits.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564641

I want to know why this happens?

Your loop is running faster than the output is being produced. As soon as it gets through the output, it ends, so it never sees the second line.

Upvotes: 1

Related Questions