Performance issues when formatting text in RichTextBox

I am creating an editor with simple syntax highlighting using RichTextBox. The process of isolating oneself is implemented using the following function:

        TextRange documentRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
        documentRange.ClearAllProperties();

        .......

        tags.Sort((i, j) => i.Level > j.Level ? 1 : i.Level == j.Level ? 0 : -1);
        Color []_colors=new Color[]{Colors.Blue,Colors.Brown,Colors.BlueViolet,Colors.Crimson,Colors.DarkBlue,
            Colors.Green,Colors.DimGray,Colors.DarkGray,Colors.Maroon,Colors.Navy,Colors.Red};
        foreach (var tag in tags)
        {
            TextRange range = new TextRange(tag.StartPosition, tag.EndPosition);
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(_colors[tag.Level%_colors.Length]));
            range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        }

The problem is that when I use this approach when there are a lot of keywords in the text, the performance of the application suffers significantly, especially that I do it every time the RichTextBoxe text changes.

I run the profiler, and it looks like the application spends half of its processor time in documentRange.ClearAllProperties ().

What should I change to improve the constancy of the application?

Can someone provide a good example of quick syntax highlighting using WPF RichTextBox?

+3
source share
1

, , , , , , . - : (psuedo-code)

OnRichTextChanged() 
{
   StopExisingSyntaxHighlighterTimer();
   StartSyntaxHighlighterTimer(TimeSpan.FromSeconds(5));
}

OnSyntaxHighlighterTimerFired() 
{
   StopExisingSyntaxHighlighterTimer();
   DoSyntaxHighlighting();
}

, , 5 , RichTextBox .

, DoSyntaxHighlighting , , , , , .

, , . .

- AvalonEdit.

+2

All Articles