ParallelOptions.MaxDegreeOfParallelism没有做任何事情

时间:2016-03-29 13:34:42

标签: c# task-parallel-library parallel.foreach

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

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,我也能看到所有核心的运行情况。

我在这里错过了这一点吗?我认为这个想法是限制线程的数量?

2 个答案:

答案 0 :(得分:6)

看起来您将po传递给Parallel.ForEach,因此它只使用默认值。使用允许您将Parallel.ForEach传递到ParallelOptions的{​​{1}} an overload,也许是这一个:

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

答案 1 :(得分:3)

您没有使用循环中定义的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);
});