当我运行以下代码时:
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 个线程执行工作?
默认情况下,For 和 ForEach 将利用底层调度程序提供的线程数,因此更改默认值 MaxDegreeOfParallelism 仅限制将使用的并发任务数。
翻译:在任何给定时刻都只会运行 2 个线程,但线程池中可能会使用多于(甚至少于)2 个线程。您可以在任务开始时使用另一个写入行进行测试,您将看到没有 3 个线程会同时进入。