【问题标题】:Parallel.for loop ExecutionParallel.for 循环执行
【发布时间】:2021-01-09 23:10:35
【问题描述】:

场景

我需要创建并行执行多个函数的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# multithreading loops parallel-processing


    【解决方案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(不包括)。因此,最多可以有两个线程。

    【讨论】:

      【解决方案2】:

      您似乎在寻找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
        );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 2021-12-26
        • 2014-03-04
        相关资源
        最近更新 更多