0

In this page, the following code is an example for changing the affinity of the current process:

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process myProcess = Process.GetCurrentProcess();
        Console.WriteLine("ProcessorAffinity: {0}", myProcess.ProcessorAffinity);
        Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)3;
        Console.WriteLine("ProcessorAffinity: {0} ", myProcess.ProcessorAffinity);
        Console.ReadKey();
    }
}

But the output for me is:

ProcessorAffinity: 255

ProcessorAffinity: 255

meaning that the affinity is not changed. What's the problem? And how can I change the affinity?

Community
  • 1
  • 1
  • 3
    Change `Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)3;` to `myProcess.ProcessorAffinity = (System.IntPtr)3;` – Chetan Oct 18 '18 at 02:51
  • 1
    Also, wrap `myProcess` in `using` statement, like this: `using (var myProcess = Process.GetCurrentProcess()) { .. }` – vasily.sib Oct 18 '18 at 02:58
  • @vasily.sib How can wrapping be helpful? –  Oct 18 '18 at 02:59
  • @nano, `Process` instance is helding some unmanaged resources, so if you not disposing it correctly - your app will leak. This is also recommended [in the docs](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netframework-4.7.2#remarks) – vasily.sib Oct 18 '18 at 03:06
  • Is your program running in elevated mode *(administrator mode)*? You can not change affinity without this. – Julo Oct 18 '18 at 03:13
  • @Julo, as I know, there is no need in elevated permissions, when you changeing affinity of your own process. Why do you think, that he can not change affinity without this? – vasily.sib Oct 18 '18 at 03:23
  • My bad. I only know, you need to have elevated permissions to change affinity, but I forgot, that this might not be the case for my own process. *(I only tested this with application1 changes affinity of application2)*. – Julo Oct 18 '18 at 03:31
  • This kind of sounds a little X/Y'ish. – TheGeneral Oct 18 '18 at 04:04

1 Answers1

1

As @ChetanRanpariya mension in his comment, the issue is because you changeing ProcessorAffinity of one process object (returned from the second call of Process.GetCurrentProcess()) and checking it in another (returned from the first call of Process.GetCurrentProcess()). Here is corrected sample:

using (var currentProcess = Process.GetCurrentProcess())
{
    Console.WriteLine($"ProcessorAffinity: {currentProcess.ProcessorAffinity}");
    currentProcess.ProcessorAffinity = (System.IntPtr)3;
    Console.WriteLine($"ProcessorAffinity: {currentProcess.ProcessorAffinity}");
}
vasily.sib
  • 3,871
  • 2
  • 23
  • 26