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

本文关键字:内核 何限制 进程 | 更新日期: 2023-09-27 18:10:17

我希望我的程序打开一些其他进程,项目的要求之一是每个打开的进程只能在单个核心上运行。

我知道可以使用processorAffinity选择特定的处理器,但是是否可以设置最大内核数(在我的情况下为1)?

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

你必须尝试使用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;
        }
    }
}