Calculating richtextbox lines count asynchronously

177 Views Asked by At

I write a code that counts the number of lines and text length from richtextbox content. With small chunks of text it work perfect. But when there large chunks of text (more than 100k) when I press "Enter" or "Backspace" in richtextbox, response time becomes very slow. For example: https://i.imgur.com/QO2UrAw.gifv

My question. What a better way to run this code asynchronously?

Archive with the test project https://gofile.io/?c=LpF409

private void StatusPanelTextInfo()
{
    int currentColumn = 0;
    int currentLine = 0;
    int linesCount = 0;
    if (statusStrip1.Visible)
    {
        currentColumn = 1 + richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexOfCurrentLine();
        RichTextBox rtb = new RichTextBox
        {
            WordWrap = false,
            Text = richTextBox1.Text
        };
        currentLine = 1 + rtb.GetLineFromCharIndex(richTextBox1.SelectionStart);
        linesCount = richTextBox1.Lines.Count();
        if (linesCount == 0)
        {
            linesCount = 1;
        }
    }
    toolStripStatusLabel1.Text = "Length: " + richTextBox1.TextLength;
    toolStripStatusLabel2.Text = "Lines: " + linesCount;
    toolStripStatusLabel3.Text = "Ln: " + currentLine;
    toolStripStatusLabel4.Text = "Col: " + currentColumn;
}
1

There are 1 best solutions below

4
ymdred16 On

I downloaded your code and I can not understand why do you create a new RichTextBox every time you call StatusPanelTextInfo method:

RichTextBox rtb = new RichTextBox
{
    WordWrap = false,
    Text = richTextBox1.Text
};

This is the reason you got such a lag in your program. Each time you change/select text, you create a new RichTextBox object and copy a large amount of text to its Text property. You should remove this code, and then it works fast enough. Just replace rtb in your calculation of currentLine with richTextBox1.

Next time please provide your code in your question instead of making people download it from outer link. Your whole form class was about 60 lines. With proper selection you could have given us all the info we needed using 20 lines.