使用多个有限数量的线程处理项目列表

Ed *_*net 2 .net c# multithreading parallel-extensions plinq

基本上,我想要处理多个线程中的项目列表,而不是一次处理一个.我一次只想要有限数量的线程.这种方法有意义吗?使用全局变量进行线程计数是唯一的选择吗?(下面的伪代码)

foreach item in list
    while thread_count >= thread_max
        sleep
    loop
    start_thread item
    thread_count++
next

function start_thread(item)
    do_something_to item
    thread_count--
end function
Run Code Online (Sandbox Code Playgroud)

Dre*_*rsh 6

我会使用PLINQ来指定最大并行度,如下所示:

我实际上是在改变这个问题的答案,因为我意识到你只是想直接处理一个原始列表而你没有做任何其他的过滤或映射(Where/Select).在这种特殊情况下,最好使用Parallel :: ForEach并通过ParallelOptions指定MaxDegreeOfParallelism,如下所示:

 int myMaxDegreeOfParallelism = 4; // read this from config maybe

 Parallel.ForEach(
    list,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = myMaxDegreeOfParallelism
    }
    item =>
    {
        // ... your work here ...
    });
Run Code Online (Sandbox Code Playgroud)

现在,请记住,当您指定这样的最大值时,即使它们可用,也会阻止PLINQ使用更多资源.因此,如果这是在8核机器上运行,它将永远不会使用超过4个核心.相反,仅仅因为你指定4,并不意味着4保证在任何给定时间同时执行.这完全取决于TPL使用的几种启发式算法.