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);
}
}
我看到输出是:
有3个线程ID这里,但我已指定的MaxDegreeOFParallelism只有2个。那么为什么有3个线程在做这个工作而不是2个呢?
http://stackoverflow.com/questions/9538452/what-does-maxdegreeofparallelism-do – christiandev
我不认为这是关于'哪些'线程,我认为这只是关于同时有多少。所以我不期望它能保证'重复使用'线程。 – Silvermind
所以你说任何时候只有2个线程在运行,而且这个id是不相关的? –