开发者

How can I add a huge string to a textbox efficiently?

开发者 https://www.devze.com 2022-12-17 14:39 出处:网络
I have a massive string (we are talking 1696108 characters in length) which I have read very quickly from a text file. When I add it to my textbox (C#), it takes ages to do. A program like Notepad++ (

I have a massive string (we are talking 1696108 characters in length) which I have read very quickly from a text file. When I add it to my textbox (C#), it takes ages to do. A program like Notepad++ (unmanaged code, I know) can do it almost instantly although Notepad takes a long time also. How can I efficiently 开发者_如何学运维add this huge string and how does something like Notepad++ do it so quickly?


If this is Windows Forms I would suggest trying RichTextBox as a drop-in replacement for your TextBox. In the past I've found it to be much more efficient at handling large text. Also when making modifications in-place be sure to use the time-tested SelectionStart/SelectedText method instead of manipulating the Text property.

rtb.SelectionStart = rtb.TextLength;
rtb.SelectedText = "inserted text"; // faster

rtb.Text += "inserted text"; // slower


Notepad and Window TextBox class is optimized for 64K text. You should use RichTextBox


You could, initially, just render the first n characters that are viewable in the UI (assuming you have a scrolling textbox). Then, start a separate thread to render successive blocks asynchronously.

Alternatively, you could combine it with your input stream from the file. Read a chunk and immediately append it to the text box. Example (not thorough, but you get the idea) ...

private void PopulateTextBoxWithFileContents(string path, TextBox textBox)
{
    using (var fs = File.OpenRead(path))
    {
        using (var sr = new StreamReader(fs))
        {
            while (!sr.EndOfStream)
                textBox.Text += sr.ReadLine();                        

            sr.Close();                    
        }

        fs.Close();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消