Roman Dzhabarov
Roman Dzhabarov

Reputation: 521

ReadToEnd from std output of process and waitforexit

From the MSDN example of using stdoutput of newly created process:

    // This is the code for the base process
    Process myProcess = new Process();
    // Start a new instance of this program but specify the 'spawned' version.
    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(args[0], "spawn");
    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();
    StreamReader myStreamReader = myProcess.StandardOutput;
    // Read the standard output of the spawned process. 
    string myString = myStreamReader.ReadLine();
    Console.WriteLine(myString);
    myProcess.WaitForExit();
    myProcess.Close();

If instead of myStreamReader.ReadLine() I'm using myStreamReader.ReadToEnd() shall I still use myProcess.WaitForExit()? Or ReadToEnd() will wait until the process is finished?

Upvotes: 2

Views: 4059

Answers (2)

Chibueze Opata
Chibueze Opata

Reputation: 10054

EDIT: Sorry for the diversion, to directly answer your question. Yes, you need to call Process.WaitForExit();. This will ensure that the process has yielded all its output before you call ReadToEnd()

ReadToEnd is synchronous function. Hence if you don't call it in your code, it will block your main thread until it captures only the first output from the StandardOutput, then that's it. But using WaitForExit will ensure that you have everything.

Also you might consider doing an asynchronous read of the process's output, see this MSDN Example that implements OutputDataRecieved

Upvotes: 2

Rikki
Rikki

Reputation: 3528

"ReadToEnd" is a function stored in "StreamReader" object and I don't think it has something to do with waiting for a process to exit, however the "Process" class might handle that itself. By the way, all the abilities "StreamReader" has are not useful in the situation you mentioned.

In my point of view, "WaitForExit" should be called and as you did "Close" too. Because they will release some system resources that no method else can. As far as I know, "ReadToEnd" method has nothing to do with calling those two.

Cheers

Upvotes: 1

Related Questions