How to set process affinity to "All processors" in C#?

1.6k views Asked by At

I've figured out how to set process affinity mask to run process on just single processor:

Process p = ... //getting required process
p.ProcessorAffinity = (IntPtr)0x0001;

But I can't figure out how to set it back to all processors. How do I do so? Thanks.

2

There are 2 answers

0
Dmitry Bychenko On

According to MSDN

https://msdn.microsoft.com/en-us/library/system.diagnostics.process.processoraffinity(v=vs.110).aspx

A bitmask representing the processors that the threads in the associated process can run on. The default depends on the number of processors on the computer. The default value is 2^n - 1, where n is the number of processors.

So you should put

Process p = ...

p.ProcessorAffinity = (IntPtr)((1 << Environment.ProcessorCount) - 1);

in order to lift the restrictions (now p can be run on any processor: we have 11...11 bitmask with N ones where N is the number of the logical processors)

0
mason On

It sounds like you want to return the affinity to the default (keep in mind, this isn't necessarily the same as all processors, the default is is 2^n -1, where n is the number of processors, see the documentation).

To return to the default, simply store the default in a variable and then reassign it.

void Main()
{
    Process p = Process.GetProcessById(12008);
    var originalAffinity = p.ProcessorAffinity;
    Console.WriteLine("Original affinity: " + originalAffinity);
    p.ProcessorAffinity = (IntPtr)0x0001;
    Console.WriteLine("Current affinity: " + p.ProcessorAffinity);
    p.ProcessorAffinity = originalAffinity;
    Console.WriteLine("Final affinity: " + p.ProcessorAffinity);    
}

Results on my machine:

Original affinity: 255

Current affinity: 1

Final affinity: 255