开发者

Cross Thread Exception with Throttle in Reactive Extensions

I am using Reactive Extensions to verification of a textbox input. I am trying to use the .Throttle(TimeSpan.FromMilliseconds(500)).

But when I add the .Throttle() method a cross thread exception is thrown when accessing a UI object in the .Subscribe() method.

It works 100% without the Throttle, why is it breaking?

My code:

 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 -开发者_C百科Oliver


By default Throttle uses the ThreadpoolScheduler so events will not arrive on the UI Thread. Since you need the events on the UI thread use:-

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

This will put the events back on the UI Thread.


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

Need to install Rx and to reference System.Reactive and System.Reactive.Windows.Threading assemblies (for LightSwitch this reference go in the Client project).

Then use this code to throttle a the TextChange event on the text box:

(Note: For lightswitch this code goes 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜