2

For example, my laptop has Intel with 2 cores and 4 logical processors. When I use the code to print info about executing thread(s), I would like to print the id of core or logical processor executing the thread. How to do it in C#

This is not a question how to get static info but dynamic info for an executing thread. As an example, this is what I use to get static info

 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);
 }

// Partial output

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
  • It would make more sense if you wrote that you have intel processor with 2 cores and 4 threads. – FCin Mar 14 '18 at 17:57
  • Possible duplicate of [How to determine which CPU a thread runs on?](https://stackoverflow.com/questions/8998895/how-to-determine-which-cpu-a-thread-runs-on) – TyCobb Mar 14 '18 at 17:58
  • 2
    Threads move unless you specifically set the affinity. – TyCobb Mar 14 '18 at 17:58
  • It is in the ProcessInfo structure. See Pinvoke : https://www.pinvoke.net/default.aspx/coredll.ProcessInfo Aslo see msdn : https://msdn.microsoft.com/en-us/library/system.web.processinfo(v=vs.110).aspx – jdweng Mar 14 '18 at 18:06

1 Answers1

4

You can use 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

Jophy job
  • 1,924
  • 2
  • 20
  • 38
  • then use WMI to get details about core link : https://code.msdn.microsoft.com/windowsdesktop/CCS-LABS-WMI-Getting-c0403bd9 – Jophy job Mar 14 '18 at 18:21
  • Seems to work for me. Note: `using System.Security;` and `using System.Runtime.InteropServices;` (and `using System.Threading;`) – BurnsBA Mar 14 '18 at 19:24