如何在 .NET 中将处理器关联设置为线程或任务? [英] How can I set processor affinity to a thread or a Task in .NET?
问题描述
我们能否在 C# 应用程序中设置两个线程或两个任务以不同的处理器关联执行?
我已经阅读了关于 SetThreadAffinityMask
的内容,但没有找到应该如何使用它的示例.
或者,有没有办法让 TPL(任务并行库)执行两个高优先级的线程/任务来使用 100% CPU?
Process
和 ProcessThread
对象具有 的
类型,可直接操作以读取/更改最多 64 个处理器的关联:ProcessorAffinity
属性IntPtr
您还可以使用线程的 IdealProcessor
属性来允许调度程序优先在指定的处理器上运行线程(不保证).
是的,就是这么简单:)
参考:MSDN ProcessThread.ProcessorAffinity 属性
Can we set two threads or two tasks to execute with different processor affinity in a C# application?
I have read about SetThreadAffinityMask
, but have found no example of how that should be used.
Alternatively, is there any way for TPL (Task Parallel Library) to execute two threads/Tasks with high priority to use 100% CPU?
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;
...
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 :)
Reference: MSDN ProcessThread.ProcessorAffinity Property
这篇关于如何在 .NET 中将处理器关联设置为线程或任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!