这个问题本质上是在问: “我如何高效,快速地从标准输入中读取信息?”
在上面的代码中,问题不在Chrome扩展程序和主机之间,而是在标准输入和从标准输入流读取的方法之间,即
StandardOutputStreamIn()。
该方法在OP代码中的工作方式是,循环在标准输入流中运行,并将
input字符串与新字符串(即从字节流中读取的字符)连续连接在一起。这是一项 昂贵的
操作,我们可以通过创建一个
StreamReader对象来立即抓取整个流来解决此问题(特别是因为我们知道前4个字节中包含的长度信息)。因此,我们通过以下方式解决了速度问题:
public static string OpenStandardStreamIn() { //Read 4 bytes of length information System.IO.Stream stdin = Console.OpenStandardInput(); int length = 0; byte[] bytes = new byte[4]; stdin.Read(bytes, 0, 4); length = System.BitConverter.ToInt32(bytes, 0); char[] buffer = new char[length]; using (System.IO.StreamReader sr = new System.IO.StreamReader(stdin)) { while (sr.Peek() >= 0) { sr.Read(buffer, 0, buffer.Length); } } string input = new string(buffer); return input; }虽然这解决了速度问题,但我不确定扩展名为何抛出
Native host has exited error。



