3

Well i am using ReactiveExtensions eventhandler to handle my application events, i also use ControlScheduler in order to run the handler on the ui thread. However, recently i am getting Cross Thread exception despite using the ControlScheduler and i don't know what is the problem

Code:

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

Isn't the new ControlScheduler(this) supposed to run the code on the UI Thread so i don't get the Cross Threading exception ?

Jim Bolla
  • 8,265
  • 36
  • 54
Roman Ratskey
  • 5,101
  • 8
  • 44
  • 67

1 Answers1

4

You should be doing

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

It is the standard way of dispatching to the scheduler related to the specific control. Passing the control schedular as you have done subscribes on the control rather than observes on it. See this answer for this difference between ObserverOn and SubscribeOn

Note the implementation of ObserveOn is from System..Reactive.Windows.Forms assembly.

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));
}
Community
  • 1
  • 1
bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217
  • 1
    Also, [see this](http://stackoverflow.com/questions/20451939/observeon-and-subscribeon-where-the-work-is-being-done) for an explanation of `ObserveOn` - the core problem is that you were subscribing on the scheduler instead of observing on it. – James World Feb 18 '14 at 08:38
  • @JamesWorld I'll update the answer to reflect that. Ta – bradgonesurfing Feb 18 '14 at 08:45