假设我有一个 IO-bound 任务。我正在使用 WithDegreeOfParallelism = 10 和 WithExecution = ForceParallelism 模式,但查询仍然只使用两个线程。为什么?
我知道 PLINQ 通常会选择与我的核心数量相等的并行度,但为什么它忽略了我对更高并行度的具体要求?
static void Main(string[] args)
{
TestParallel(0.UpTo(8));
}
private static void TestParallel(IEnumerable<int> input)
{
var timer = new Stopwatch();
timer.Start();
var size = input.Count();
if (input.AsParallel().
WithDegreeOfParallelism(10).
WithExecutionMode(ParallelExecutionMode.ForceParallelism).
Where(IsOdd).Count() != size / 2)
throw new Exception("Failed to count the odds");
timer.Stop();
Console.WriteLine("Tested " + size + " numbers in " + timer.Elapsed.TotalSeconds + " seconds");
}
private static bool IsOdd(int n)
{
Thread.Sleep(1000);
return n%2 == 1;
}