Why is asynchronous reading not completed even after the process is complete?

I wrote a process that reads data from a file specified as an argument. I read StandardOutput asynchronously and StandardError synchronously.

public static string ProcessScript(string command, string arguments)
{
        Process proc = new Process();
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.FileName = command;
        proc.StartInfo.Arguments = arguments;
        proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
        proc.Start();
        string error = null;
        string output = null;
        proc.OutputDataReceived += (sender, outputLine) => 
        { 
            if (outputLine.Data != null) 
            {
                output += outputLine.Data;
            }
        };
        proc.BeginOutputReadLine();
        error = proc.StandardError.ReadToEnd();
        proc.WaitForExit();
        proc.Close();

        //I have not got entire Output
        return output;
} 

After the process is complete, I get the output. But not really. I receive only partial data. Asynchronous reading is not completed even after the process has completed, so I only get partial data. I need the full line that is specified.

Edit:

I am using .Net 3.5. I can not use ReadToEndAsyncMethod

Any ideas?

+3
source share
3 answers

, , , ( , .NET 4.5, ).

public static string ProcessScript(string command, string arguments)
{
    Process proc = new Process();
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;
    proc.StartInfo.FileName = command;
    proc.StartInfo.Arguments = arguments;
    proc.Start();

    var output = proc.StandardOutput.ReadToEndAsync();
    var error = proc.StandardError.ReadToEndAsync();
    proc.WaitForExit();
    proc.Close();
    var errorContent = error.Result;
    return output.Result;
}

Task, ReadToEndAsync, , , . , , , , .

+4

, WaitForExit . , Reflector, . , .

, : , null, . .

, - . .

0

fooobar.com/questions/44191/...

WaitForExit() ( ) WaitForExit(timeout) true:

if (process.WaitForExit(timeout) && process.WaitForExit())
{
    // do stuff: async read will be completed here
}

: https://msdn.microsoft.com/en-us/library/ty0d8k56(v=vs.110).aspx

0

All Articles