Search code examples
c#parallel-processingparallelism-amdahl

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

  • 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)
    );