Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Reactive.Concurrency.DefaultScheduler

In my application I've written all of my Rx code to use Scheduler.Default. I wanted to know if there's a difference between specifying Scheduler.Default and not specifying a scheduler at all?

What is the strategy employed by System.Reactive.Concurrency.DefaultScheduler?

like image 462
Amir Shitrit Avatar asked Oct 01 '13 08:10

Amir Shitrit


2 Answers

Rx uses an appropriate strategy dependent on the platform specific PlatformServices that are loaded - hence you can have a different approach in different cases. The OOB implementation looks at whether Threads are available on your platform, and if so uses Threads and the platform Timer implementation to schedule items, otherwise it uses Tasks. The later case arises in Windows 8 Apps, for example.

You can find a good video about how platform services are implemented from the creator here: http://channel9.msdn.com/Shows/Going+Deep/Bart-De-Smet-Rx-20-RTM-and-RTW

Look here for information about how the built-in operators behave when you do and don't specify a scheduler: http://msdn.microsoft.com/en-us/library/hh242963(v=vs.103).aspx

like image 103
James World Avatar answered Oct 17 '22 18:10

James World


Yes there is a difference between specifying Scheduler.Default and not specifying a scheduler. Using Scheduler.Default will introduce asynchronous and possibly concurrent behavior, while not supplying a scheduler leaves it up to the discretion of the operator. Some operators will choose to execute synchronously while others will execute asynchronously, while others will choose to jump threads.

It is probably a bad idea (for performance and possibly even correctness since too much concurrency might lead you into a deadlock situation) to supply Scheduler.Default to every Rx operator. If you do not have a specific scheduling requirement, then do not supply a scheduler and let the operator pick what it needs.

For example,

this will complete synchronously:

int result = 0;
Observable.Return(42).Subscribe(v => result = v);
result == 42;

while this will complete asynchronously (and likely on another thread):

int result = 0;
Observable.Return(42, Scheduler.Default).Subscribe(v => result = v);
result == 0;

// some time later
result == 42;
like image 23
Brandon Avatar answered Oct 17 '22 18:10

Brandon