在.NET中使用BinaryReader重定向标准输出 - 检测EOS / 强制超时

3
我正在从C# NET 4应用程序中的进程重定向标准输出,然后在单独的线程上使用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);
        }
1个回答

1

Process.Exited事件只有在您将Process.EnableRaisingEvents设置为true时才会触发。如果您这样做了,您应该通过Process.Exited或同步的Process.WaitForExit方法获得进程退出通知。

如果您仍然没有收到此事件,请检查您的子进程是否正常终止(即使是这样,我仍然希望Exited能够触发)。


谢谢Chris,我不知道这个。你的答案没有让我检测到流的结束,或者让BinaryReader超时,但是它确实让我能够实现我在问题中提到的解决方法,所以我将其标记为被接受的答案。 - Carlos P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接