我试图使用StreamReader从进程读取输出数据,但是StreamReader会阻塞并且不会返回任何输出。
我的流程如下:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = args;
startInfo.FileName = filename;
StartInfo.WorkingDirectory = aDirectory;
StartInfo.UseShellExecute = false;
StartInfo.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = startInfo;
p.Start();StreamReader随后就被调用了:
StreamReader strmRead = p.StandardOutput;
char[] output = new char[4096];
while(true){
strmRead.Read(output,0,output.Length);
string outputString = new string(output);
Debug.WriteLine(outputString);
}代码挂起对Read方法的调用。当我手动终止程序时,进程的输出将被写入调试控制台。流程输出不使用换行符,因此使用Process.OutputDataReceived不起作用。如何在不无限期阻塞的情况下从流中获取流程输出?
编辑:给出了我已经得到的答案,这个过程没有放弃标准输出,或者没有刷新输出,这似乎是一个问题,而不是我的代码有什么问题。如果其他人有任何洞察力,可以随意评论。
发布于 2012-05-31 18:28:46
您正在读取4096字节,并且可能会有更少的流块。
此外,还有更有效的方法从流中读取文本。TextReader有ReadLine方法,试一试。
http://msdn.microsoft.com/en-us/library/system.io.textreader.readline.aspx
顺便说一句,while (true)?你打算怎么退出?
发布于 2012-05-31 18:32:01
你可以这么做:
String outputString = strmRead.ReadToEnd();发布于 2014-07-27 09:50:53
我知道这个问题很老。但我也有类似的问题。我尝试使用Peek()方法,但是即使当Peek()返回-1时,它也并不总是流的末尾。
我通过启动一个新线程来解决我的问题,该线程试图在Peek()返回-1时读取下一个字符。
string toRead = "";
do
{
if (reader.Peek() == -1)
{
Thread td = new Thread(TryReading);
td.Start();
Thread.Sleep(400);
if (ReadSuccess == false)
{
try
{
td.Abort();
}
catch (Exception ex) { }
break;
}
else
{
toRead += ReadChar;
ReadSuccess = false;
}
}
toRead += (char)reader.Read();
} while (true);TryReading()方法在这里定义:
static char ReadChar = 'a';
static bool ReadSuccess = false;
static void TryReading(object callback)
{
int read = reader.Read();
ReadChar = (char)read;
ReadSuccess = true;
}基本上..。如果线程花了很长时间才读到字符--我中止了它,并使用它读取的文本到目前为止。
这解决了我的问题。
https://stackoverflow.com/questions/10839106
复制相似问题