Question

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 ?

Was it helpful?

Solution

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));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top