小编典典

MaxDegreeOfParallelism做什么?

c#

我正在使用Parallel.ForEach并且正在进行一些数据库更新,现在没有设置MaxDegreeOfParallelism,双核处理器机器会导致sql客户端超时,而其他四核处理器机器会以某种方式不会超时。

现在,我无法控制运行代码的处理器类型,但是我可以使用MaxDegreeOfParallelism更改某些设置,这些设置可能会同时运行较少的操作,并且不会导致超时吗?

我可以增加超时时间,但这不是一个好的解决方案,如果在较低的CPU上我可以同时处理较少的操作,则可以减轻cpu的负担。

好的,我也阅读了所有其他文章和MSDN,但是将MaxDegreeOfParallelism设置为较低的值会使我的四核计算机受苦吗?

例如,如果CPU有两个内核,则使用20,如果CPU有四个内核,则使用40?


阅读 846

收藏
2020-05-19

共1个答案

小编典典

答案是,这是整个并行操作的上限,与内核数无关。

因此,即使由于等待IO或锁定而没有使用CPU,也不会并行运行额外的任务,只会执行您指定的最大值。

为了找到答案,我编写了这段测试代码。那里有一个人为锁,以刺激TPL使用更多线程。当您的代码等待IO或数据库时,也会发生同样的情况。

class Program
{
    static void Main(string[] args)
    {
        var locker = new Object();
        int count = 0;
        Parallel.For
            (0
             , 1000
             , new ParallelOptions { MaxDegreeOfParallelism = 2 }
             , (i) =>
                   {
                       Interlocked.Increment(ref count);
                       lock (locker)
                       {
                           Console.WriteLine("Number of active threads:" + count);
                           Thread.Sleep(10);
                        }
                        Interlocked.Decrement(ref count);
                    }
            );
    }
}

如果我未指定MaxDegreeOfParallelism,则控制台日志将显示最多同时运行约8个任务。像这样:

Number of active threads:6
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:6
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7

它开始时较低,随时间增加,最后尝试同时运行8。

如果我将其限制为任意值(例如2),我得到

Number of active threads:2
Number of active threads:1
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2

哦,这是在四核计算机上。

2020-05-19