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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With