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

前端 未结 1 718
轻奢々
轻奢々 2020-12-06 23:48

I am using Chrome\'s Native Messaging API to pass the DOM of a page to my host. When I try passing a small string from my extension to my host, everything works, but when I

相关标签:
1条回答
  • 2020-12-07 00:30

    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.

    0 讨论(0)
提交回复
热议问题