2013-12-22 22 views
2

当我运行下面的代码:MaxDegreeOfParallelism = 2只示出了3个线程

public static double SumRootN(int root) 
    { 
     double result = 0; 
     for (int i = 1; i < 10000000; i++) 
     { 
      result += Math.Exp(Math.Log(i)/root); 
     } 
     return result; 
    } 

static void Main() 
{ 
    ParallelOptions options = new ParallelOptions(); 
    options.MaxDegreeOfParallelism = 2; // -1 is for unlimited. 1 is for sequential. 

    try 
    { 
     Parallel.For(
       0, 
       9, 
       options, 
       (i) => 
     { 
      var result = SumRootN(i); 
      Console.WriteLine("Thread={0}, root {0} : {1} ",Thread.CurrentThread.ManagedThreadId, i, result); 
     }); 
      ); 

    } 
    catch (AggregateException e) 
    { 
     Console.WriteLine("Parallel.For has thrown the following (unexpected) exception:\n{0}", e); 
    } 
} 

我看到输出是: enter image description here

有3个线程ID这里,但我已指定的MaxDegreeOFParallelism只有2个。那么为什么有3个线程在做这个工作而不是2个呢?

+0

http://stackoverflow.com/questions/9538452/what-does-maxdegreeofparallelism-do – christiandev

+0

我不认为这是关于'哪些'线程,我认为这只是关于同时有多少。所以我不期望它能保证'重复使用'线程。 – Silvermind

+0

所以你说任何时候只有2个线程在运行,而且这个id是不相关的? –

回答

4

报价从http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(v=vs.110).aspx

默认情况下,和foreach将利用然而,许多线程的基本调度程序提供,所以从默认的改变MaxDegreeOfParallelism唯一的限制很多并发任务将被如何使用。

翻译:在任何给定时刻只有2个线程正在运行,但是可以在线程池外使用更多(甚至更少)2个线程。你可以在任务开始时用另一条写入线来测试,你会看到没有3个线程同时进入。

相关问题