per0xid3
per0xid3

Reputation: 33

How to access WPF controls from a background thread

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.

Upvotes: 1

Views: 781

Answers (1)

CharithJ
CharithJ

Reputation: 47570

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}));

Upvotes: 6

Related Questions