Futures

Futures are tasks which allow you to perform some calculation in parallel, and get the result at a later date.

Example 1:
Future<float> pi = Tasked.Do<float>(CalculatePiTo5Places); // CalculatePiTo5Places takes no arguments and returns a float.
float x = DoSomeOtherWork();
return x + pi.Result;

The Tasked.Do call creates and starts a future, which will begin to perform the "CalculatePiTo5Places" method.
This future will store the answer in the futures' Result property once it has completed the calculation. However, getting Result implicitly does a Wait() on the task, so you can retrieve the result at any time, save in the knowledge that the answer will be calculated when Result returns.

You can also pass in parameters.

Example 2:
Future<float, int> pi = Tasked.Do<float, int>(CalculatePi, 5); // CalculatePi takes a single int argument, and returns a float.
float x = DoSomeOtherWork();
return x + pi.Result;

This code starts a future with the CalculatePi method, and passes in 5 for the arguement.

If you are using VS2008, the syntax is much more readable, thanks to the type inference and var keyword.
var pi = Tasked.Do(CalculatePi, 5);
float x = DoSomeOtherWork();
return x + pi.Result;

Last edited Aug 10, 2008 at 12:40 PM by Aphid, version 1

Comments

No comments yet.