.net Observed 'ObserveOn' background thread

I am trying to implement a simple Observer pattern using the .net Observable class. I have a code that looks like this:

 Observable.FromEventPattern<PropertyChangedEventArgs>( Instance.User, "PropertyChanged") .Where(e => e.EventArgs.PropertyName == "FirstName") .ObserveOn(Scheduler.ThreadPool) .Subscribe(search => OnFirstNameChanged(search.EventArgs)); Observable.FromEventPattern<PropertyChangedEventArgs>( Instance.User, "PropertyChanged") .Where(e => e.EventArgs.PropertyName == "LastName") .ObserveOn(Scheduler.ThreadPool) .Subscribe(search => OnLastNameChanged(search.EventArgs)); 

I want the watchers to run in the background thread, but I want them all to work on the same background thread (for our real implementation, it will be too difficult for each listener to use a different thread).

i.e. I want all OnXXXChanged logic OnXXXChanged execute in a thread other than the user interface thread, but instead of Observing to the entire thread pool, I want to make sure that they work in the correct order, in the same thread.

How should I change this above?

Also, in some related post, are there any good examples of examples using the Observable class to implement this pattern?

+6
source share
2 answers

You must create an EventLoopScheduler and use this single instance in all ObserverOn calls:

 var scheduler = new EventLoopScheduler(ts => new Thread(ts)); ... .ObserveOn(scheduler). ... 

The thread created by the factory method is the thread used to schedule execution. If you leave the ExitIfEmpty property false , this thread will not terminate, even if there is nothing to do so that it is reused for each call.

However, you can also use Scheduler.NewThread . Using this scheduler will allow the thread to exit if there is nothing more to do. When more work is queued using ObserverOn , a new thread will be created, but there should be only one thread, meaning that you do not have synchronization of different observers.

Threads created by EventLoopScheduler (which are used by Scheduler.NewThread ) are called Event Loop # . You will see these names in the debugger.

+13
source

.ObserveOn(Scheduler.ThreadPool) accepts a thread scheduler that defines the thread being monitored. It looks like for a single thread you want to use EventLoopScheduler , not ThreadPool.

+5
source

Source: https://habr.com/ru/post/906770/


All Articles