Monday, October 24, 2011

Obtaining Results from Parallel Tasks

Task Results

So far in our examination of parallel tasks we have looked at the Task class. This allows an action delegate to be executed with the possibility of parallelism. The delegate can access variables that are outside of its scope in order to communicate with the main thread of execution or with other tasks, allowing you to simulate a return value. However, an alternative Task class is available for more elegant generation of return values.

The Task<T> generic class inherits much of its functionality from its non-generic counterpart. Tasks are created using a delegate, often a lambda expression, started using the Start method and executed in parallel where it is efficient to do so. The key difference is that the lambda expression returns a value of the type defined by the task's type parameter. This return value can be accessed by reading the task's Result property.

The Task<T> class is found in the System.Threading.Tasks namespace so to simplify the examples, add the following using directive:
using System.Threading.Tasks;

As with other parallel and multi-threaded scenarios, synchronisation is required. In this case, it is necessary to ensure that the result of a parallel task is not read before it has been set. Luckily, the Task Parallel Library takes care of this for you. If you attempt to read the result too early, the current thread is blocked until the task has completed executing. This is the same as calling the Wait method manually before reading the result.

The following sample shows the use of a parallel task with a return value. Here a long calculation is performed and the returned result is extracted from the Result property. You can see that the main thread is blocked until the parallel calculation completes to ensure that the correct value is obtained.

Task<long> taskWithResult = new Task<long>(() =>
    long total = 0;
    for (int i = 1; i < 1000000000; i++);    // Adjust this loop according
    {                                        // to your computer's speed
        total += i;
    return total;

Console.WriteLine("Result = {0}", taskWithResult.Result);


Result = 499999999500000000


Read more: BlackWasp
QR: TaskResult.aspx

Posted via email from Jasper-Net