【问题标题】:Cross Thread Exception with Throttle in Reactive Extensions反应式扩展中带有节流的跨线程异常
【发布时间】:2011-01-14 12:31:42
【问题描述】:

我正在使用响应式扩展来验证文本框输入。 我正在尝试使用 .Throttle(TimeSpan.FromMilliseconds(500))。

但是当我添加 .Throttle() 方法时,在 .Subscribe() 方法中访问 UI 对象时会引发跨线程异常。

没有油门,它可以 100% 工作,为什么会坏掉?

我的代码:

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

谢谢 -奥利弗

【问题讨论】:

    标签: silverlight exception system.reactive


    【解决方案1】:

    默认情况下Throttle 使用ThreadpoolScheduler,因此事件不会到达 UI 线程。由于您需要 UI 线程上的事件,请使用:-

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

    这会将事件放回 UI 线程。

    【讨论】:

    • +1 不能信任任何具有IScheduler 重载的运算符与调用者在同一线程上运行。最好使用IScheduler 重载而不是使用ObserveOn
    • 其实我相信它在.NET 4中默认为ThreadPoolScheduler
    • 太棒了,刚开始使用 RX。多谢你们。 @Richard,感谢您对 IScheduler 的建议...我现在会注意的。
    • 顺便说一句:它是 SL4 中的 Scheduler.Dispatcher 供其他人查看。
    • @Oliver:你说得对,我读的是类型而不是属性名称;答案已编辑。
    【解决方案2】:

    由于自提出此问题以来 Rx 中的一些接口更改,我不得不稍微调整代码以使其在具有 Rx v1.0.10621 的 LightSwitch (SilverLight 4) 应用程序中工作。

    需要install Rx 并引用System.ReactiveSystem.Reactive.Windows.Threading 程序集(对于LightSwitch,此引用进入Client 项目)。

    然后使用此代码来限制文本框上的TextChange 事件:

    (注意:对于电灯开关,此代码位于 ControlAvailable 处理程序中)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多