Reading lots of characters and updating a textbox

﹥>﹥吖頭↗ 提交于 2019-12-24 00:33:57

问题


I am reading data from a stream (provided by a process) character by character and adding it to a textbox so the user can see. The only problem is, this is SLOW. The user needs to see the data as it is given to the program (with little to no delay). I would like something like how terminals handle text, it can scroll by so fast that it's a blur.

How can I improve this?

For reference, I'm using C# .net3.5 and winforms.


回答1:


The Text property of the text box is a string, and strings are immutable (meaning that you can't change a string). This means that each time that you add a character, you will be creating a new copy of the string with one character added at the end.

If you for example have 10000 characters in the textbox, you will be copying 20kB of data to add the next character. Adding a hundred characters one at a time means copying 2MB of data.

If the data is line based, use a list instead of a text box, so that you only have to update the last line when you add a character.




回答2:


In a multiline textbox you'll get slightly better performance by using the Selection to append chars:

textBox1.Select(textLength, 0);
textBox1.Selectedtext = newText;
textLength += newText.Length;

But as you can see you'll have to track the Length yourself and this method will probably break if you allow control-chars (like backspace).

I would recommend Guffa's idea of using a listbox first.




回答3:


Some code would help to figure out what the bottleneck is.

That said, I'd try something along these lines (I wouldn't suggest copy/paste as I can't test it here):

// Stream s...
byte[] buffer = new buffet[bufferSize];
s.BeginRead(b, 0, buffer.Length,
    delegate
        {
            if (textBox1.InvokeRequired)
            {
                textBox1.Invoke(
                    new MethodInvoker(
                        delegate 
                        { 
                            textBox1.Text = Encoding.Unicode.GetString(b); 
                        }));
            }
            else
            {
                textBox1.Text = Encoding.Unicode.GetString(b);
            }
         }, null);


来源:https://stackoverflow.com/questions/660159/reading-lots-of-characters-and-updating-a-textbox

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