我有一个可执行程序,它可以立即从命令提示符中运行,但是当使用System.Diagnostics.Process生成时似乎永远不会返回:
基本上,我正在编写一个围绕Accurev CLI接口的.NET库包装器,因此每个方法调用都会产生CLI进程来执行命令。
这个对所有命令都很有效,只有一条命令例外:
accurev.exe show depots
然而,从控制台运行此代码时,它可以正常运行,但当我使用 .net 进程调用它时,它会挂起... 我使用的进程生成代码是:
public static string ExecuteCommand(string command)
{
Process p = createProcess(command);
p.Start();
p.WaitForExit();
// Accurev writes to the error stream if ExitCode is non zero.
if (p.ExitCode != 0)
{
string error = p.StandardError.ReadToEnd();
Log.Write(command + " failed..." + error);
throw new AccurevException(error);
}
else
{
return p.StandardOutput.ReadToEnd();
}
}
/// Creates Accurev Process
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private static Process createProcess(string command)
{
Log.Write("Executing Command: " + command);
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();
startInfo.CreateNoWindow = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = _accurev;
p.StartInfo = startInfo;
return p;
}
它无法进行,卡在了p.WaitForExit()。
任何建议? (Rènhé jiànyì?)
编辑:已解决!
.NET 进程如果输出缓冲区溢出,将会挂起,我转而使用异步读取方法,一切都正常了。
public static string ExecuteCommand(string command)
{
StringBuilder outputData = new StringBuilder();
Process p = createProcess(command);
p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
outputData.AppendLine(e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
// Accurev writes to the error stream if ExitCode is non zero.
if (p.ExitCode != 0)
{
string error = p.StandardError.ReadToEnd();
Log.Write(command + " failed..." + error);
throw new AccurevException(error);
}
else
{
return outputData.ToString();
}
}