我正在从C# NET 4应用程序中的进程重定向标准输出,然后在单独的线程上使用BinaryReader读取它(这是二进制数据;需要解析定界符的视频块)。
一切都很好,直到进程输出最后一个字节,此时BinaryReader挂起,在ReadBytes(int)上阻塞。这对我来说不好,我需要知道流何时结束,以便将最后一块数据写入磁盘。
我会使用Process.Exited事件,并将其视为EOS(然后终止线程)。但是Process.Exited从未被触发:可能进程正在等待我的应用程序关闭流之前死亡。
不幸的是,this question似乎表明任何对StandardOutput的更高级属性的调用,例如StandardOutput.EndOfStream,都会导致访问StandardOutput的默认StreamReader,因此我认为这种方法行不通。
有没有简单的方法可以检测流的结束,或使BinaryReader超时?
一切都很好,直到进程输出最后一个字节,此时BinaryReader挂起,在ReadBytes(int)上阻塞。这对我来说不好,我需要知道流何时结束,以便将最后一块数据写入磁盘。
我会使用Process.Exited事件,并将其视为EOS(然后终止线程)。但是Process.Exited从未被触发:可能进程正在等待我的应用程序关闭流之前死亡。
不幸的是,this question似乎表明任何对StandardOutput的更高级属性的调用,例如StandardOutput.EndOfStream,都会导致访问StandardOutput的默认StreamReader,因此我认为这种方法行不通。
有没有简单的方法可以检测流的结束,或使BinaryReader超时?
{
runningProcess.Start();
// Read standard output on a new thread
thrdReadStandardOut = new Thread(new ThreadStart(ReadStandardOutput));
thrdReadStandardOut.Start();
}
...
void ReadStandardOutput()
{
Monitor.Enter(runningProcess); // keep this section thread safe
var br = new BinaryReader(runningProcess.StandardOutput.BaseStream);
bool abort = false;
while (!abort)
{
try
{
byte[] bytes = br.ReadBytes(256);
if (StandardOutputReceived != null)
StandardOutputReceived(this, new GenericEventArgs<byte[]>(bytes));
}
catch (EndOfStreamException)
{
abort = true;
}
}
Monitor.Exit(runningProcess);
}