To set the affinity of CPUs using C#

前端 未结 4 1496
甜味超标
甜味超标 2021-02-09 23:26

I have created a window application in C#.Now I want to set the CPU affinity for this application.I may have 2 processors,4 processors,8 processors or may be more than 8 process

4条回答
  •  不思量自难忘°
    2021-02-10 00:01

    System.Diagnostics.Process.ProcessorAffinity

    What do you want to use Environment.ProcessorCount for? User input validation? Anyway if you want to select a particular processor (#1 or #2 or #3...), create a bitmask like that:

    if (userSelection <= 0 || userSelection > Environment.ProcessorCount)
    {
        throw new ArgumentOutOfRangeException();
    }
    
    int bitMask = 1 << (userSelection - 1);
    Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)bitMask;
    

    Where userSelection - is a number of selected processor.

    If you'd like to select more than one processor, then do

    bitMask |= 1 << (anotherUserSelection - 1);
    

    for each user selection

提交回复
热议问题