C# Question

A code example illustrating the difference between the paradigms of async/await and Reactive (Rx) extension?

Both the System.Reactive extension for .NET and new C# 5.0 (.NET 4.5)

pursue (or based on) future and promises constructs paradigm (approach).

Can you give the (*) simplest C# code example illustrating the difference between them?


Is it possible without I/O, internet or database connections?


Well, let me reformulate if this question seemed to be answered before.

Why would one add and start using Reactive (Rx) extensions for .NET while using native .NET Iobservable/IObserver + await/async?

What are the possible illustrations of what one will be missing from Rx that made to do the same more clumsy or less efficient without Rx (i.e. engaging just native .NET Iobservable/IObserver + await/async approach)?

Answer Source

The Future/Promise paradigm generally is used for returning a single value in the future. Perhaps there is some heavy calculation or IO that is required and hence why it can not be guaranteed to be return synchronously in a timely manner.

Rx (and by proxy the IObserver<T>/IObservable<T> interfaces) is a paradigm of observable sequences. Just as a synchronous method could return a single value (int), it could also return an IEnumerable<int> with one value. Comparing this to an asynchronous world, Task<int> can return a single int value, IObservable<int> could return a sequence with just one int value.

So if you wanted to return a sequence of values with Task<T>, you would have to either create some sort of continuation, or return a collection/array/list of values as the T e.g. Task<int[]>. This however will mean you get all or non of the values.

Task/Task<T> is also a concrete type, where as Rx uses interfaces to abstract you from implementation. I have found this to help in unit testing. TaskCompletionSource<T> however can be helpful to avoid implicit concurrency when testing with tasks.

Finally, besides the main difference that Rx is dealing with sequences of values (not single values), Rx is also designed to work with LINQ to deliver the querying and composition benefits that seems to work very well with sequences (either at rest like IEnumerable<T>, or in motion like IObservable<T>).

Ultimately these are different tools for slightly different jobs. There is some overlap, so you sometimes can use one to do what the other is better at. To be specific, I think Task is better at composing units of asynchronous work together (Do this, then do that, then do this), where as Rx is better at composing sequences of events together (When this event happens, do this with data from this other event).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download