'Evaluating methods in parallel

Let's say I need the output from the below independent methods

var x = LongCalculation(123)
var y = LongCalculation2(345)
var z = LongCalculation3(678)
var b = LongCalculation4(910)

What is the least code invasive way of executing these calculations in parallel, without destroying the readability of the logic? I know of Parallel.Foreach() but in this case there is no list of items to process, only independent method calls.



Solution 1:[1]

I guess the least invasive way is using Parallel.Invoke:

long x, y, z, b;
Parallel.Invoke(
    () => x = LongCalculation(123),
    () => y = LongCalculation2(345),
    () => z = LongCalculation3(678),
    () => b = LongCalculation4(910)
);

Solution 2:[2]

You can make a list of items to process out of your code:

int x,y,z,b;
List<Action> actions = new List<Action>
{
    () => x = LongCalculation(123),
    () => y = LongCalculation2(345),
    () => z = LongCalculation3(678),
    () => b = LongCalculation4(910)
};
Parallel.ForEach(actions, x => x.Invoke());

Online demo: https://dotnetfiddle.net/xy7sxF

Solution 3:[3]

Using the Task.Run and the Task.WaitAll should be quite readable:

var task1 = Task.Run(() => LongCalculation(123));
var task2 = Task.Run(() => LongCalculation2(345));
var task3 = Task.Run(() => LongCalculation3(678));
var task4 = Task.Run(() => LongCalculation4(910));
Task.WaitAll(task1, task2, task3, task4);
var x = task1.Result;
var y = task2.Result;
var z = task3.Result;
var b = task4.Result;

This assuming that limiting the degree of parallelism of the CPU-bound operations is not a requirement.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clemens
Solution 2 SomeBody
Solution 3 Theodor Zoulias