简体   繁体   English

如何限制进程使用的内核数?

[英]How do I limit the number of cores used for a process?

I want my program to open some other processes, and one of the requirements of the project is that each process opened can only be run on a single core. 我希望我的程序打开其他一些进程,并且该项目的要求之一是,每个打开的进程只能在单个内核上运行。

I know that a specific processor can be picked with processorAffinity but is it possible to set a maximum number of cores (in my case 1)? 我知道可以使用processorAffinity选择特定的处理器,但是是否可以设置最大内核数(在我的情况下为1)?

you have to try with ProcessThread.ProcessorAffinity 您必须尝试使用ProcessThread.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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM