I have built a program that loads Xaml into a
RichTextBox
, and then goes through the text sentence by sentence, using
Regex
to find words against a glossary.
From the
Regex Matches
, I then create
TextRange
s (from
TextPointer
s, determined by the
Match.Index
, by counting from the
Document.ContentStart
), and I keep these in a
List<TextRange>
.
I then Highlight each
TextRange
in the List by using
TextRange.ApplyPropertyValue(TextBlock.BackgroundProperty, myHighlightBrush)
.
This procedure has to be done for each sentence, so each time, I clear the
List
and then recalculate the
TextPointer
s for the next sentence.
(The
TextRange
s need to be kept in the running
List
in order to access the text of those ranges later).
After a lot of trial-and-error I've gotten the program to do exactly what I want, but there is a problem:
When I use it continuously for more than an hour or so, the procedure becomes progressively slower, and through some debugging I've been able to narrow the slowing part to the actual highlighting of the TextRanges.
If the program is closed and reopened, and started from the previous point, the highlighting speed is acceptable again, and predictably after an hour or so, it starts to become maddeningly sluggish again.
What I have tried:
Some things I have tried are:
1) Run.Background highlighting instead of TextBlock, i.e.
TextRange.ApplyPropertyValue(Run.BackgroundProperty, myHighlightBrush);
2) Reinstantiating the List instead of clearing it, i.e.
List<TextRange> ranges = new List<TextRange>();
But it seems not to have any effect in terms of progressive slowing.
What I'm wondering is, what is happening to all of those
TextPointer
s I've been creating along the way? I can't find any way to dispose of the old ones, so are they automatically disposed of? If not, could they be slowing things down, since presumably the
RichTextBox
has to do heuristic calculations for each
TextPointer
whenever a change is made to it. Or maybe all these TextPointers are just causing memory leaks?
Is clearing the List enough to rid the
RichTextBox
of the previous
TextPointer
s and
TextRange
s?
I can't find any information on the net about what happens to
TextPointer
s after you're done using them...