为什么我无法获取线程的 ProcessorAffinity?
Why I can't get the ProcessorAffinity of a thread?
我正在制作 CPU 使用统计的程序。我有一个列表Processes, each one with its Process.Threads. For each thread, I want to know its current affinity to know which CPU Core it is binded to, but ProcessThread.ProcessAffinity只能设置...不能读取!
为什么?有没有办法获取这些信息?
此外,我可以不调用低级 Win32 函数而只调用 .NET Standards 来获取它吗?
在@oliver-rogier 的提示下,我设法通过使用函数设置掩码(从 C++ 导入)来完成。如文档中所述:
Return value
If the function succeeds, the return value is the thread's previous affinity mask.
[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;
}
我正在制作 CPU 使用统计的程序。我有一个列表Processes, each one with its Process.Threads. For each thread, I want to know its current affinity to know which CPU Core it is binded to, but ProcessThread.ProcessAffinity只能设置...不能读取!
为什么?有没有办法获取这些信息?
此外,我可以不调用低级 Win32 函数而只调用 .NET Standards 来获取它吗?
在@oliver-rogier 的提示下,我设法通过使用函数设置掩码(从 C++ 导入)来完成。如文档中所述:
Return value
If the function succeeds, the return value is the thread's previous affinity mask.
[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;
}