-1

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.

rsod
  • 57
  • 4
  • You're assuming it *was* set to all processors -- maybe it was launched differently. Why not get the value of `p.ProcessorAffinity` first and restore it afterwards? – Jeroen Mostert Sep 12 '17 at 13:25
  • 5
    Did you bother [reading the documentation](https://msdn.microsoft.com/en-us/library/system.diagnostics.process.processoraffinity(v=vs.110).aspx)? – mason Sep 12 '17 at 13:26
  • 1
    @mason how does that link answer this question? – CodeCaster Sep 12 '17 at 13:34
  • @CodeCaster He's asking how to set it "back to all processors". Meaning he somehow set it to all processors before and forgot how (unlikely) or incorrectly thinks the default is "all processors". Reading the documentation would correct that misimpression, and explains how to set it to run on however many processors you want. Seems relevant. You disagree? – mason Sep 12 '17 at 13:36
  • @Jeroen Mostert This is genious. How didn't I thought about it? Thank you very much, works perfectly. – rsod Sep 12 '17 at 13:39

2 Answers2

1

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)

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

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

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121