ParallelOptions.MaxDegreeOfParallelism 什么都不做

ParallelOptions.MaxDegreeOfParallelism not doing anything

使用 MSDN article 上关于 ParallelOptions.MaxDegreeOfParallelism 的代码,我尝试了以下...

ParallelOptions po = new ParallelOptions {
  MaxDegreeOfParallelism = 2
};
Parallel.ForEach(files, (currentFile) => {
  String filename = System.IO.Path.GetFileName(currentFile);
  Bitmap bitmap = new Bitmap(currentFile);
  bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
  bitmap.Save(Path.Combine(newDir, filename));
  Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);
});

但是,查看正在输出的线程 ID,我可以看到是否设置 MaxDegreeOfParallelism 根本没有任何区别。查看我的 CPU 监视器,我可以看到所有内核都在运行,即使我将 MaxDegreeOfParallelism 设置为 2。

我是不是漏掉了重点?我以为这个想法是限制线程数?

您似乎没有将 po 传递给 Parallel.ForEach,所以它只是使用默认值。使用 Parallel.ForEachan overload 允许您将 ParallelOptions 传递到,也许是这个:

Parallel.ForEach(files, po, (currentFile) => {

您没有使用您在循环中定义的 ParallelOptions。您必须使用不同的重载:

Parallel.ForEach<TSource> Method (IEnumerable<TSource>, ParallelOptions, Action<TSource>)

https://msdn.microsoft.com/en-us/library/dd783747(v=vs.110).aspx

ParallelOptions po = new ParallelOptions {
  MaxDegreeOfParallelism = 2
};
Parallel.ForEach(files, po, (currentFile) => {
  String filename = System.IO.Path.GetFileName(currentFile);
  Bitmap bitmap = new Bitmap(currentFile);
  bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
  bitmap.Save(Path.Combine(newDir, filename));
  Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);
});