我编写了一个进程,它从作为参数给出的文件中读取数据。我已经异步读取 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;
}
Run Code Online (Sandbox Code Playgroud)
该过程完成后,我正在获得输出。但不完全。我只得到部分数据。即使在进程完成其任务后,异步读取也没有结束,所以只有我得到了部分数据。我需要给出的完整字符串。
编辑:
我正在使用 .Net 3.5。我不能使用ReadToEndAsync方法
有任何想法吗?
您可以直接从实际输出流中读取数据,而不是处理事件和处理事件产生的问题(假设您使用的是 .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;
}
Run Code Online (Sandbox Code Playgroud)
在这里,由Task表示的ReadToEndAsync实际上不会完成,直到它拥有其结果所表示的全部数据。这意味着您要等到获得所有数据,而不是等待过程完成,因为这两个可能不会完全同时发生。