如何设置在.NET处理器关系?处理器、如何设置、关系、NET

由网友(北陌)分享简介:我们可以设置两个线程或两个任务与不同的处理器亲和力在C#应用程序中执行?Can we set two threads or two tasks to execute with different processor affinity in a C# application?我看了一下 SetThreadAffin...

我们可以设置两个线程或两个任务与不同的处理器亲和力在C#应用程序中执行?

Can we set two threads or two tasks to execute with different processor affinity in a C# application?

我看了一下 SetThreadAffinityMask ,但已经找到了如何应使用无例子。

I have read about SetThreadAffinityMask but have found no example of how that should be used.

另外,有没有办法为TPL(任务并行库),以执行两个线程/任务具有高优先使用100%的CPU?

Alternatively, is there any way for TPL (Task Parallel Library) to execute two threads/Tasks with high priority to use 100% CPU?

推荐答案

进程 ProcessThread 对象有一个 ProcessorAffinity 的IntPtr 键入可直接操作的读取/修改亲和力多达64个处理器:

Process and ProcessThread objects have a ProcessorAffinity property of IntPtr type that can be directly manipulated to read/change affinity for up to 64 processors:



using System.Diagnostics;
...
  Process Proc = Process.GetCurrentProcess();
  long AffinityMask = (long)Proc.ProcessorAffinity;
  AffinityMask &= 0x000F; // use only any of the first 4 available processors
  Proc.ProcessorAffinity = (IntPtr)AffinityMask;

  ProcessThread Thread = Proc.Threads[0];
  AffinityMask = 0x0002; // use only the second processor, despite availability
  Thread.ProcessorAffinity = (IntPtr)AffinityMask;
...

您也可以使用线程的 IdealProcessor ​​属性,以允许调度preFER运行指定处理器(没有担保)的主题。

You can also use the thread's IdealProcessor property to allow the scheduler to prefer running the thread on a specified processor (without guarantee).

是的,就是这么简单:)

Yes, it's that easy :)

参考:MSDN ProcessThread.ProcessorAffinity物业