如何在.NET中设置处理器相关性?

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

我已经阅读了关于SetThreadAffinityMask但没有发现如何应用的例子。

或者,TPL(任务并行库)是否有任何方法执行两个线程/高优先级的任务使用100%的CPU?

ProcessProcessThread对象具有IntPtrtypes的ProcessorAffinity属性,可以直接操作以读取/更改最多64个处理器的关联:

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; ...
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属性来让调度程序更喜欢在指定的处理器上运行线程(不保证)。

是的,就这么简单:)

参考: MSDN ProcessThread.ProcessorAffinity属性

实际上操作系统是能够负载平衡你的内核/处理器,但如果你想要做到这一点明确使用通过PInvoke提到。 你传递线程的id(不是pipe理的)!和掩码 – 内核的比特数组。

以下MSDN示例演示如何将Notepad实例的ProcessorAffinity属性设置为第一个处理器。

 using System; using System.Diagnostics; namespace ProcessThreadIdealProcessor { class Program { static void Main(string[] args) { // Make sure there is an instance of notepad running. Process[] notepads = Process.GetProcessesByName("notepad"); if (notepads.Length == 0) Process.Start("notepad"); ProcessThreadCollection threads; //Process[] notepads; // Retrieve the Notepad processes. notepads = Process.GetProcessesByName("Notepad"); // Get the ProcessThread collection for the first instance threads = notepads[0].Threads; // Set the properties on the first ProcessThread in the collection threads[0].IdealProcessor = 0; threads[0].ProcessorAffinity = (IntPtr)1; } } }