设置内核的并行使用内核

2023-09-04 08:38:29 作者:娇柔可人儿

我有一种感觉这个问题的答案是否定的,但使用.NET 4.0中的并行,你能设定核心在其上运行也就是说,如果你运行的是四核的数量,你可以设置你只使用应用程序其中2?

I have a feeling the answer to this is no, but using .Net 4.0's Parallelism, can you set the amount of cores on which to run i.e. if your running a Quad Core, can you set your Application to only use 2 of them?

感谢

推荐答案

是的,是的Parallel.For的内置功能()。使用接受一个ParallelOptions对象重载之一,设置它的MaxDegreeOfParallelism属性。例如:

Yes, it is a built-in capability of Parallel.For(). Use one of the overloads that accepts a ParallelOptions object, set its MaxDegreeOfParallelism property. For example:

using System;
using System.Threading.Tasks;

class Program {
  static void Main(string[] args) {
    var options = new ParallelOptions();
    options.MaxDegreeOfParallelism = 2;
    Parallel.For(0, 100, options, (ix) => {
      //..
    });
  }
}