Parallel.for循环执行

时间:2020-09-23 17:23:39

标签: c# multithreading loops parallel-processing

场景

我需要创建n个线程(与要执行的功能数量不相等的线程),这些线程可以并行执行多个功能。所以我的代码是

    static void Main() 
    { 
        Parallel.For(0, 2, i => // it creates 2 threads as number of iterations.why?
            {
                  method1();
                  method2();
                  method3();
                  method4();
                  method5();
                  method6();
                  method7();
                  method8();
                  method9();
                  method10();
            });
     }

如何以最佳方式在此处使用MaxDegreeOfParallelism属性?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

似乎您正在寻找Parallel.Invoke而不是Parallel.For(在您的代码中看不到任何循环):

  ParallelOptions options = new ParallelOptions() {
    //TODO: carry out experiment on your workstation to find out the right number
    MaxDegreeOfParallelism = 4, 
  };

  // Run method1..method10 in parallel while using options 
  Parallel.Invoke(options,
    method1,
    method2,
    method3,
    method4,
    method5,
    method6,
    method7,
    method8,
    method9,
    method10
  );

答案 1 :(得分:1)

如你所愿

var methods = new Action[] {
    method1, method2, method3, method4, method5, method6, method7, method8, method9, method10 };

Parallel.For(0, methods.Length, i =>
{
    methods[i]();
});

这样您可以设置并行度

var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };

Parallel.For(0, methods.Length, options, i =>

编写Parallel.For(0, 2时,它将为指定数量的元素创建一个循环:从0(含)到2(不含)。因此,最多可以有两个线程。

相关问题