如何获取执行线程的核心/处理器ID?

时间:2018-03-14 17:53:30

标签: c#

例如,我的笔记本电脑配备2核和4个逻辑处理器的英特尔。 当我使用代码打印有关执行线程的信息时,我想 打印执行该线程的核心或逻辑处理器的id。如何在C#

中完成

这不是一个如何获取静态信息而是执行线程的动态信息的问题。举个例子,这就是我用来获取静态信息的方法

 ManagementClass mc = new ManagementClass("win32_processor");
 ManagementObjectCollection mColl = mc.GetInstances();
 foreach (ManagementObject mObj in mColl)
 {
     PropertyDataCollection pDC = mObj.Properties;
     foreach (PropertyData pd in pDC)
        Console.WriteLine("  {0} - {1}", pd.Name, pd.Value);
 }

//部分输出

Caption - Intel64 Family 6 Model 78 Stepping 3
Description - Intel64 Family 6 Model 78 Stepping 3
DeviceID - CPU0
Name - Intel(R) Core(TM) i3 - 6006U CPU @ 2.00GHz
NumberOfCores - 2
NumberOfEnabledCore - 2
NumberOfLogicalProcessors - 4
SocketDesignation - U3E1
ThreadCount - 4   // probably threads of hyper-threading, not process threads

1 个答案:

答案 0 :(得分:0)

您可以使用GetCurrentProcessorNumber

[DllImport("Kernel32.dll"), SuppressUnmanagedCodeSecurity]
public static extern int GetCurrentProcessorNumber();

static void Main(string[] args)
{
    Parallel.For (0, 10 , state => Console.WriteLine("Thread Id = {0}, CoreId = {1}",
        Thread.CurrentThread.ManagedThreadId,
        GetCurrentProcessorNumber()));
    Console.ReadKey();
}

how-to-find-which-core-your-thread-is-scheduled-on