如何一次异步读取标准输出流和标准错误流 [英] How to asynchronously read the standard output stream and standard error stream at once

查看:28
本文介绍了如何一次异步读取标准输出流和标准错误流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以控制台中的形式读取进程的输出(标准输出与一个流中的标准错误混合).有没有办法做到这一点?

I want to read the ouput of a process in the form as is in a console (standard output is blended with standard error in one stream). Is there a way how to do it?

我正在考虑使用

ProcessStartInfo.UseShellExecute = true;  

但是我无法异步读取输出.如果我设置

but then I cannot read asynchronously the output. If I set

process.ProcessStartInfo.UseShellExecute = false;  
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(partialOutputHandler);

然后我可以读取标准输出(我可以对标准错误执行相同的操作)但我不知道如何模拟控制台的行为(stdout 和 stderr 的混合).

then I can read standard output (I can do the same for standard error) but I don't know how to simulate the behavior of console (the blending of stdout and stderr).

这类似于Linux,具有将标准错误流重定向到标准输出流的特性;怎么样?

This is similar to Linux which has the feature of redirecting standard error stream to the standard output stream; how?

推荐答案

我找到了答案:

输出流被缓冲.没有办法得到真实插入到流中的项目的顺序.事实上它没有意义,因为两个流也可以同时写入时间.它们彼此独立.因此,你能做到的最好做的是在每个人到达时获取它们的顺序输出.

The output streams are buffered. There is no way to get the true sequential order of the items inserted into the streams. In fact it makes little sense as both streams can be written too at the same time. They are independent of each other. Therefore the best you can do is get the sequential output from each one as they arrive.

通常这不是问题,因为几乎所有控制台应用程序都使用输出和错误消息的标准输出.错误流被某些应用程序使用,但消息通常是重复的输出流中产生的错误.

Generally this is not an issue though as almost all console apps use standard output for both output and error messages. The error stream is used by some apps but the messages are generally duplicates of the errors generated in the output stream.

来源: http://social.msdn.microsoft.com/Forums/uk/csharpgeneral/thread/192b6df7-9437-42cf-81c1-c125021735ba

这篇关于如何一次异步读取标准输出流和标准错误流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆