我写过一个从作为参数给出的文件中读取数据的进程。 我已经同步读取StandardOutput和StandardError。即使在进程终止后,为什么还没有完成异步读取?
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;
}
该过程完成后,我得到输出。但不完全。我只获得部分数据。 即使在该过程完成其任务后,异步读取仍未结束,因此只有获取部分数据。我需要给出完整的字符串。
编辑:
我正在使用.net 3.5。我不能使用ReadToEndAsync
方法
任何想法?
使用* both * OutputDataReceived和BeginOutputReadLine()是一个错误。 –
@HansPassant:谢谢你指出。但在这个例子http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.process.beginoutputreadline,我发现两者都被使用。 – BinaryMee
我也看到了这个问题,我用thread.sleep解决了它。也许输出事件是在单独的线程中引发的,这意味着任意延迟。这个API设计似乎强制这个错误,并使其不可避免。 – usr