1

我正在编写一个使用本机消息传递的 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 由于没有找到数据而返回零,因此它一直在循环。

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

4

0 回答 0