ObserveOn(Scheduler.CurrentThread) doesn't cause subscribed Action to be run on original thread

末鹿安然 提交于 2019-12-08 16:59:33

You probably have the wrong understanding of what Scheduler.CurrentThread does. I think everyone makes this mistake.

The CurrentThread scheduler relates to the executing observable and not when it is defined (or subscribed to). Think deferred or lazy execution. This should make sense as whenever you jump to a different thread you need some way of marshalling the call.

So what you're really after is something like this:

var synchContext = new SynchronizationContextScheduler(
    System.Threading.SynchronizationContext.Current) 

subject
    .ObserveOn(synchContext)
    .Subscribe(callback, OnError);

Or maybe:

subject
    .ObserveOn(this) /* this is my current form */
    .Subscribe(callback, OnError);

If you do that you should be able to control which thread your callbacks get run on.

Your tests probably worked because they ended up executing synchronously.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!