-1

I have an application written in C# WPF that has a tree/folder structure which displays an ObservableCollection containing many items.

There is a filter feature where a user can input values and a search will be automatically performed and updated live on the main UI. Similar to where if you are searching something on Google's search engine and an AutoSuggestion box pops out which updates every time you enter a new character or word.

There is a scenario where if the collection has MANY datasets (over 100,000 items) and as soon as i start backspacing the values I've inputted (ex. from after inputting abcd into the textbox to abc to ab from backspacing) the main UI of my application freezes and just completely crashes the program. I figured creating a separate thread to perform this action (turning the method to an async and using await Task.Run() as follows would be the simplest solution but Visual Studio is telling me that a thread outside of the main UI thread cannot make changes to the Observable Collection. After a quick google search it seems like this is actually not suggested so I want to know if there are any other ways to get around this?

nwahs
  • 21
  • 3

2 Answers2

-1

Do the search on a separate thread and then re-enter the UI thread to put the result into the collection.

Dan
  • 858
  • 7
  • 18
-2

As the error says, you can't modify an ObservableCollection from outside the UI thread.

Fortunately, there is the Dispatcher which allows you to switch context to another thread and run things at will, like so:

Application.Dispatcher.Invoke( () => myCollection.Add(myObj) )

Which will run synchronously from the main/UI thread. To do something asynchronously use BeginInvoke() instead of Invoke()

electroball09
  • 93
  • 1
  • 3
  • 8