简体   繁体   中英

When using System.Diagnostic Process, will I miss some output lines between the start of process and start of capturing output?

If I have code such as

proc.Start();
string resultOut;

while ( (!proc.HasExited && (resultOut = stdOut.ReadLine()) != null))
{
// Do some operation based on resultOut
}

Am I liable to miss some lines from when I start proc to when the capturing/parsing begins or will it wait? If it doesn't what can I do?

If you're redirecting the input and/or output of the process via ProcessStartInfo.RedirectStandardOutput , etc, the process output will go directly to your streams. You won't miss any input or output.

The following code will not lose any lines from stdout.

var startInfo = new ProcessStartInfo
{
    FileName = "my.exe",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

using (var process = new Process { StartInfo = startInfo })
{
    process.ErrorDataReceived += (s, e) =>
    {
        string line = e.Data;            
        //process stderr lines

    };

    process.OutputDataReceived += (s, e) =>
    {
        string line = e.Data;
        //process stdout lines
    };

    process.Start();

    process.BeginErrorReadLine();
    process.BeginOutputReadLine();

    process.WaitForExit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM