31

This is the example microsoft presents for the parallel for, and I'd like to know how configure a maximum number of threads for this code.

     // A basic matrix multiplication.
     // Parallelize the outer loop to partition the source array by rows.
     System.Threading.Tasks.Parallel.For(0, matARows, i =>
     {
        for (int j = 0; j < matBCols; j++)
        {
           // Use a temporary to improve parallel performance.
           double temp = 0;
           for (int k = 0; k < matACols; k++)
           {
              temp += matA[i, k] * matB[k, j];
           }
           result[i, j] = temp;
        }
     }); // Parallel.For
Alex. S.
  • 143,260
  • 19
  • 55
  • 62
  • Is that *really* the example presented? Because it's really invalid at the moment. Could you show where that's presented? – Jon Skeet Apr 10 '13 at 16:27
  • Yeah. Well, here I only presented the relevant fragment. The whole example is here: http://msdn.microsoft.com/en-us/library/dd460713.aspx – Alex. S. Apr 10 '13 at 16:34
  • You presented a fragment which is syntactically incorrect, by sticking "System.Threading.Tasks.TaskCreationOptions" in the middle of the argument list for no reason. – Jon Skeet Apr 10 '13 at 16:48
  • Oops! Sorry, I was blind to what you were saying. Fixed. – Alex. S. Apr 10 '13 at 16:51
  • possible duplicate of [Limit the number of parallel threads in C#](http://stackoverflow.com/questions/8853907/limit-the-number-of-parallel-threads-in-c-sharp) – Sergey Malyutin Oct 16 '14 at 13:47

3 Answers3

50

You need to specify a ParallelOptions value with a MaxDegreeOfParallelism:

For example:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 4 }, count =>
{
    Console.WriteLine(count);
});
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    for Parallel for each use : Parallel.ForEach(lines,new ParallelOptions { MaxDegreeOfParallelism = 4 }, line => { Console.WriteLine(line); }); – Somnath Kadam Jul 27 '19 at 09:14
4

Use MaxDegreeOfParalelism property for running the loop

Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, ...);
Sasha
  • 8,537
  • 4
  • 49
  • 76
4

I'd suggest you take a look at the ParallelOption.MaxDegreesofParellelism and pass it into the For method

Tyler Lee
  • 2,736
  • 13
  • 24