如何在Parallel.For中配置最大线程数

时间:2013-04-10 16:25:40

标签: c# for-loop parallel-processing

这是microsoft为parallel提供的示例,我想知道如何为此代码配置最大线程数。

     // 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

3 个答案:

答案 0 :(得分:37)

您需要使用MaxDegreeOfParallelism指定ParallelOptions值:

例如:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 4 }, count =>
{
    Console.WriteLine(count);
});

答案 1 :(得分:3)

使用MaxDegreeOfParalelism属性来运行循环

Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, ...);

答案 2 :(得分:3)

我建议您查看ParallelOption.MaxDegreesofParellelism并将其传递给For方法