gpt4 book ai didi

c# - C# 中的事件驱动标准输入

转载 作者:行者123 更新时间:2023-11-30 16:06:57 24 4
gpt4 key购买 nike

当在 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);
}
}

最佳答案

轮询循环不会消耗太多 CPU,因为 ReadLine 会阻塞并等待。将此代码放在自己的工作线程中,并从中引发您的事件。据我所知,.NET 中没有这样的功能。

编辑:首先我在这里错了。更正:

您实际上可以从标准输入读取二进制数据,如this SO answer说:

To read binary, the best approach is to use the raw input stream - here showing something like "echo" between stdin and stdout:

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);
}
}

关于c# - C# 中的事件驱动标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31512409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com