【发布时间】:2015-10-09 08:01:34
【问题描述】:
当在stdin stream 上为我自己的进程接收数据时,C# 是否提供事件? Process.OutputDataReceived 之类的东西,只有我需要 InputDataReceived 的事件。
我搜索了高低,并学会了redirect stdin->stdout、monitor output streams of spawned apps 和大量其他内容,但没有人显示收到标准输入时触发了哪个事件。除非我在 main() 中使用愚蠢的轮询循环。
// dumb polling loop -- is this the only way? does this consume a lot of CPU?
while ((line = Console.ReadLine()) != null && line != "") {
// do work
}
另外,我需要从流中获取二进制数据,如下所示:
using (Stream stdin = Console.OpenStandardInput())
using (Stream stdout = Console.OpenStandardOutput())
{
byte[] buffer = new byte[2048];
int bytes;
while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0) {
stdout.Write(buffer, 0, bytes);
}
}
【问题讨论】:
-
您希望该事件用于流程(从外部)还是您自己的流程?
-
为什么需要这个活动?除非您编写多线程程序,否则事件的行为与循环读取没有任何不同。
-
@PanagiotisKanavos - 明白了。这是个好主意。