Home > Code Samples > Rx – Calling a long running function asynchronously

Rx – Calling a long running function asynchronously

August 25th, 2010 Leave a comment Go to comments

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.

Categories: Code Samples Tags:
  1. April 8th, 2011 at 17:22 | #1

    I don’t see a way in this approach to catch if there is an Exception thrown in LifeTheUniverseEverything(), do you?

    • Bryan Anderson
      April 8th, 2011 at 17:27 | #2

      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.

  2. April 8th, 2011 at 17:38 | #3

    Ah, perfect. That avoids me from having to write a “DoWork” wrapper method to call LifeTheUniverseEverything() wrapped in a try-catch.

  1. No trackbacks yet.