为什么我无法获得线程的ProcessorAffinity?

时间:2019-11-07 11:00:13

标签: c# process cpu affinity

我正在编写一个用于CPU使用率统计的程序。我有一个Processes的列表,每个列表都有其Process.Threads。对于每个线程,我想知道其当前的亲和力,以了解其绑定到哪个CPU内核,但是只能设置ProcessThread.ProcessAffinity……不可读!

为什么?有没有办法获取这些信息?

而且,我可以不调用低级Win32函数而只需调用.NET Standard来获取它吗?

1 个答案:

答案 0 :(得分:1)

在@ oliver-rogier提示之后,我设法通过使用设置掩码(从C ++导入)的功能来做到这一点。如文档中所述:

  

返回值

     

如果函数成功,则返回值是线程的先前亲和力掩码。

[DllImport(@"kernel32.dll", SetLastError = true)]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);


public static IntPtr GetThreadAffinityMask(uint threadId)
{
    Thread.BeginThreadAffinity();

    // get the handle
    IntPtr hThread = OpenThread(ThreadAccess.SET_INFORMATION | ThreadAccess.QUERY_INFORMATION, false, threadId);
    if (hThread == INVALID_HANDLE_VALUE)
    {
        var err = GetLastError();
        return IntPtr.Zero;
    }

    // there is no "get" for affinity mask, but the "set" function returns the mask before the operation
    // so first set a temp mask to obtain the current one
    IntPtr old = SetThreadAffinityMask(hThread, new IntPtr((int)Math.Pow(2, Environment.ProcessorCount)) - 1);
    if (old == IntPtr.Zero)
    {
        var err = GetLastError();
        return old;
    }

    // then restore the original value
    SetThreadAffinityMask(hThread, old);

    CloseHandle(hThread);
    Thread.EndThreadAffinity();

    return old;
}