How to parallelize for loops in C#

I’ve previously written about parallelizing C/C++ for loops with OpenMP. Many of the concepts explained in that article also apply to C#. The main difference is that C# does not use OpenMP. For loops are instead parallelized using the Parallel.For function:

Parallel.For(0,n, i =>
{
    result[i]=func(data[i]);
});

Parallel.ForEach is also available.

It might be necessary to set the number of threads equal to the number of cores:

Parallel.For(0,n, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, i => 
{ 
    result[i]=func(data[i]);
});

According to Microsoft’s documentation, the workload is distributed dynamically, so there’s no need to work with different scheduling schemes.

Leave a comment

Your email address will not be published. Required fields are marked *