Rx – Calling a long running function asynchronously
Time for a little more Rx love. Today we’re going to call a long running function asynchronously and handle the return on the Dispatcher thread almost as simply as calling the function directly.
void CallSomeLongFunctionAsync()
{
Observable
.ToAsync<int>(LifeTheUniverseEverything)()
.ObserveOnDispatcher()
.Subscribe(theAnswer => MessageBox.Show(string.Format("The answer was {0}. What was the question anyway?", theAnswer)));
}
private int LifeTheUniverseEverything()
{
Thread.Sleep(600000);
return 42;
}
I may have used my new-found powers to calculate the answer to life, the universe, and everything but imagine a service call or long running file operation. Making those UIs completely non-blocking just got a lot easier.


I don’t see a way in this approach to catch if there is an Exception thrown in LifeTheUniverseEverything(), do you?
The Subscribe method has multiple overloads which allow you to specify what should happen if LifeTheUniverseEverything throws an exception. It’s really useful if your long-running function is actually a WCF service call because it allows you to Abort() the connection rather than just Close() it.
Ah, perfect. That avoids me from having to write a “DoWork” wrapper method to call LifeTheUniverseEverything() wrapped in a try-catch.