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是不相關的? –