【问题标题】:Reactive Extensions ControlScheduler反应式扩展 ControlScheduler
【发布时间】:2014-02-18 16:48:22
【问题描述】:

我正在使用 ReactiveExtensions 事件处理程序来处理我的应用程序事件,我还使用 ControlScheduler 来在 ui 线程上运行处理程序。但是,尽管使用了 ControlScheduler,但最近我得到了 Cross Thread 异常,我不知道是什么问题

代码:

Observable.FromEventPattern<string>(cc, "UiAlertMessage", new ControlScheduler(this)).Subscribe(_ =>
{
    AlertControl.Show(this, Language.Title, _.EventArgs.UppercaseFirst());
});

new ControlScheduler(this) 不是应该在 UI 线程上运行代码,所以我没有得到跨线程异常吗?

【问题讨论】:

    标签: c# system.reactive


    【解决方案1】:

    你应该这样做

    Observable.FromEventPattern<string>(cc, "UiAlertMessage")
        .ObserveOn(this)
        .Subscribe(_ =>
        {
            AlertControl.Show(this, Language.Title, _.EventArgs.UppercaseFirst());
        });
    

    这是标准的调度方式,用于与具体控件相关的调度器。像您在控件上完成 subscribes 而不是 observes 那样传递控制计划。有关ObserverOnSubscribeOn 之间的区别,请参阅this answer

    注意ObserveOn 的实现来自System..Reactive.Windows.Forms 程序集。

    public static IObservable<TSource> ObserveOn<TSource>
    (this IObservable<TSource> source, Control control)
    {
      if (source == null)
        throw new ArgumentNullException("source");
      if (control == null)
        throw new ArgumentNullException("control");
      else
        return Synchronization.ObserveOn<TSource>(source, (IScheduler) new ControlScheduler(control));
    }
    

    【讨论】:

    • 另外,see this 解释了ObserveOn - 核心问题是您订阅了调度程序而不是观察它。
    • @JamesWorld 我将更新答案以反映这一点。塔
    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 2011-08-27
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多