C# 如何在等待输入时阻止标准输入?

C# 如何在等待输入时阻止标准输入?,c#,stdin,nativeapplication,C#,Stdin,Nativeapplication,我正在编写一个Chrome扩展,它使用本机消息传递,一切正常。我在本机应用程序端解决的问题 Chrome扩展使用stdin和stdout与本机应用程序进行通信,我很难找到一种好的方法来监听输入 现在,我的代码如下所示: using (Stream stdin = Console.OpenStandardInput(), stdout = Console.OpenStandardOutput()) { while (true) { var in

我正在编写一个Chrome扩展,它使用本机消息传递,一切正常。我在本机应用程序端解决的问题

Chrome扩展使用stdin和stdout与本机应用程序进行通信,我很难找到一种好的方法来监听输入

现在,我的代码如下所示:

using (Stream stdin = Console.OpenStandardInput(),
          stdout = Console.OpenStandardOutput())
{

    while (true)
    {
        var input = ReadInputFromStream(stdin);

        if (input == string.Empty)
        {
            System.Threading.Thread.Sleep(50);

            continue;
        }

        // Do some work and send response
    }
}
以及ReadInputStream方法:

private static string ReadInputFromStream(Stream stream)
{
    var buff = new byte[4];

    stream.Read(buff, 0, 4);

    var len = BitConverter.ToInt32(buff, 0);

    buff = new byte[len];
    stream.Read(buff, 0, len);

    return Encoding.UTF8.GetString(buff);
}
我真的希望避免睡眠,而是在收到输入之前阻止应用程序。由于找不到数据,Stream.Read返回零,因此它会继续循环


对于这个问题有一个很好的解决方案吗?

您使用的是什么.NET版本?“实现将阻塞,直到至少可以读取一个字节的数据”,来自。意思是说,他睡觉是没有必要的。哦,我现在只看你收到的0。这是一个文件结束指示器。您的输入已空运行。该结束程序了。(但实际上,我看不到您的代码检查
Read()的返回值)
。您如何知道它返回了0?感谢您的评论。我不想关闭该程序。它需要继续运行。
Read
的返回值被放入变量
buff
,该变量被返回并在代码的第一部分使用(在while循环中)。