当我运行以下代码时:
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个thread Id,但是我已经指定了MaxDegreeOFParallelism只有2。那为什么是3个thread而不是2个呢?
最佳答案
默认情况下,For 和 ForEach 将利用底层调度程序提供的线程数,因此更改默认的 MaxDegreeOfParallelism 只会限制将使用的并发任务数。
翻译:在任何给定时刻只有 2 个线程在运行,但线程池中可能会使用更多(甚至更少)线程。您可以在任务开始时用另一个 writeline 对此进行测试,您会看到没有 3 个线程会同时进入。
关于c# - MaxDegreeOfParallelism = 2 显示 3 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20733051/