Throttle cross thread exclusion

I am using Reactive Extensions to check text box input. I am trying to use .Throttle (TimeSpan.FromMilliseconds (500)).

But when I add the .Throttle () method, when calling the user interface object in the .Subscribe () method, a cross-stream exception is thrown.

It works 100% without a throttle, why does it break?

My code is:

var textChangedEvent = Observable.FromEvent<TextChangedEventArgs>(usernameTextbox, "TextChanged") .Throttle(TimeSpan.FromMilliseconds(500)) textChangedEvent.Subscribe(changed => { TextBox oUsernameTextBox = changed.Sender as TextBox; //Accessing oUsernameTextBox throws Cross Thread Exception }); 

Thanks -Oliver

+4
source share
2 answers

By default, Throttle uses ThreadpoolScheduler , so events will not appear in the user interface thread. Since you need events in the user interface thread, use: -

 var textChangedEvent = Observable.FromEvent<TextChangedEventArgs>(usernameTextbox, "TextChanged") .Throttle(TimeSpan.FromMilliseconds(500), Scheduler.Dispatcher); 

This will return the events back to the user interface thread.

+4
source

I had to modify the code a bit to work in the LightSwitch (SilverLight 4) application with Rx v1.0.10621 due to some interface changes in Rx since this question was asked.

You must install Rx and reference the System.Reactive and System.Reactive.Windows.Threading assemblies (for LightSwitch, this link is in the Client project).

Then use this code to throttle the TextChange event in a text field:

(Note: For highlighting, this code is included in the ControlAvailable handler)

 var textChangedEvent = Observable .FromEventPattern<TextChangedEventArgs>(e.Control, "TextChanged") .Throttle(TimeSpan.FromMilliseconds(500)) .ObserveOnDispatcher(); textChangedEvent.Subscribe(changed => { var tb = changed.Sender as TextBox; if (tb.Text.Length >= 3) // don't search for keywords shorter than 3 chars { // search } }); 
0
source

Source: https://habr.com/ru/post/1335544/


All Articles