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 parallell, 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.
CodePudding user response:
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)
);
CodePudding user response:
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
CodePudding user response:
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.