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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15931346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:31:43  来源:igfitidea点击:

How to configure a maximum number of threads in a Parallel.For

c#for-loopparallel-processing

提问by Alex. S.

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

采纳答案by Jon Skeet

You need to specify a ParallelOptionsvalue with a MaxDegreeOfParallelism:

您需要指定一个ParallelOptionsMaxDegreeOfParallelism

For example:

例如:

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

回答by Sasha

Use MaxDegreeOfParalelismproperty for running the loop

使用MaxDegreeOfParalelism属性运行循环

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

回答by Tyler Lee

I'd suggest you take a look at the ParallelOption.MaxDegreesofParellelismand pass it into the Formethod

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