WHen我运行以下代码:
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个线程Ids,但是我已经指定MaxDegreeOFParallelism只有2,那么为什么有3个线程而不是2个线程来做这项工作呢?
发布于 2013-12-23 03:23:54
默认情况下,For和ForEach将利用底层调度器提供的线程数,因此更改MaxDegreeOfParallelism的默认值只会限制将使用的并发任务数。
翻译:在任何给定时刻,只有2个线程在运行,但线程池中使用的线程数可能会超过2个。您可以在任务开始时使用另一个写入行进行测试,您将看到不会有3个线程并发进入。
https://stackoverflow.com/questions/20733051
复制相似问题