1

I have a RichTextBox and I'm trying to find and highlight all words that match a user supplied query. The code I have works, but for rather large documents, it hangs the UI, since everything is done on the UI thread.

List<TextRange> getAllMatchingRanges(String query)
    {
        TextRange searchRange = new TextRange(ricthBox.Document.ContentStart, ricthBox.Document.ContentEnd);
        int offset = 0, startIndex = 0;
        List<TextRange> final = new List<TextRange>();
        TextRange result = null;

        while (startIndex <= searchRange.Text.LastIndexOf(query))
        {
            offset = searchRange.Text.IndexOf(query, startIndex);

            if (offset < 0)
                break;
            }

            for (TextPointer start = searchRange.Start.GetPositionAtOffset(offset); start != searchRange.End; start = start.GetPositionAtOffset(1))
            {
                if (start.GetPositionAtOffset(query.Length) == null)
                    break;
                result = new TextRange(start, start.GetPositionAtOffset(query.Length));
                if (result.Text == query)
                {
                    break;
                }
            }
            if (result == null)
            {
                break;
            }
            final.Add(result);

            startIndex = offset + query.Length;
        }

        return final;

    }

This will return a list of text ranges which I can then highlight, but I cant execute it on background thread as it throws an exception since I'd be trying to access the richTextbox's document on a thread that didn't create it.

1 Answer 1

6

One option is Dispatcher's background priority. Let the highlighting to happen in background without blocking the UI thread.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => {// Do your highlighting}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.