We use TextChanged event to do some operations when the content of textbox changed. It's okay to do some easy operations in TextChanged event but if you want to do some high-cost operation like database querying or IO operating in frequent-triggered event like TextChanged and ValueChanged, the UI will slow down with many unexpected bugs.
The truth is: we don't want to handle this event every time but just when user finished typing.
There is a class library design for parallel programming which can be quite helpful in this case and it's called Reactive Extensions(Rx), developed by Microsoft. This class library can help us to finish the task(handle the TextChanged event just when user finished typing)
Talk is cheap. Show me the code
First, we need to get Rx from nuget.
using System.Reactive.Linq; in your backend code.
Add a event handler for
MainPage.Loaded, handle this event every time when MainPage loaded.
Add the following codes into method
Observable.FromEventPattern<AutoSuggestBoxTextChangedEventArgs>(this.QueryBox, "TextChanged").Throttle(TimeSpan.FromMilliseconds(500)).Subscribe(async x => do some work);
Remember to replace AutoSuggestBoxTextChangedEventArgs with the right type of event args and change this.QueryBox into the right event sender.
Throttle(this IObservable<TSource> source, TimeSpan dueTime) is to ignores elements from an observable sequence which are followed by another element within a specified relative time duration. In our code, we let it to ignore the event triggered in 500ms(just handle the last event in event sequence)and use
Subscribe<T>(this IObservable<T> source, Action<T> onNext) to subscribe the event and add the event handler operation.
Reactive Extensions is such a powerful library and the knowledge mentioned in this passage is just the tip of the iceberg. Full guide of Rx can be found on MSDN.
p.s. WPF offers a Delay property in data binding which can also finish the work above. Unfortunately, this Delay property hasn't been supported in UWP yet