Very Slow to pass “large” amount of data from Chrome Extension to Host (written in C#)

不问归期 提交于 2019-11-28 01:41:18

This question is essentially asking, "How can I efficiently and quickly read information from the standard input?"

In the above code, the problem is not between the Chrome extension and the host, but rather between the standard input and the method that reads from the standard input stream, namely StandardOutputStreamIn().

The way the method works in the OP's code is that a loop runs through the standard input stream and continuously concatenates the input string with a new string (i.e. the character it reads from the byte stream). This is an expensive operation, and we can get around this by creating a StreamReader object to just grab the entire stream at once (especially since we know the length information contained in the first 4 bytes). So, we fix the speed issue with:

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

While this fixes the speed problem, I am unsure why the extension is throwing a Native host has exited error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!