Carl Nolan’s ramblings on development
In a previous post I talked about some options around performing parallel executions by providing some wrappers that allowed a collection of functions to be executed in parallel:
However there is another approach one could take.
The main challenge in performing parallel code using Tasks in F# is managing and casting objects to the correct types. If one just needs to initialize a future task and gather the result later in the execution path, one option is an implementation of a simpler Future type:
This type is initialized with a function that is executed using a Task, thus returning immediately. The caller can then get the execution result, when needed, by calling the Get() method.
In the case of non-value returning function, the Func mapping still works as a call to Get() will return “unit”.
The Future type not only simplifies starting up parallel tasks but also simplifies the process of cancelling them. All one has to do is call Cancel() without the need to manage cancellation tokens.
To use this type one can write code such as:
It may come as no surprise that this code takes 8 seconds to execute.
An alternative approach to the implementation is to define an object hierarchy of FutureTask and FutureTask<’T> such as:
In this implementation a distinction is made between running a value-returning function, FutureTask<’T>, and a non-value returning function, FutureTask. These are mapped to as Task with a Func and Action respectively.