首页 > 解决方案 > Parallel.for 循环执行

问题描述

设想

我需要创建并行执行多个函数的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最佳方式使用这里的财产?有人可以帮忙吗?

标签: c#multithreadingloopsparallel-processing

解决方案


看来您正在寻找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
  );

推荐阅读