I have some code that needs to know how many actual cores are available on my particular machine, and whether or not Hyperthreading is enabled.
Is there a way to do this in C#?
Update: The machines are a mix of XP and Vista
Update: Accessing 'Win32_Processor.NumberOfCores' or 'Win32_Processor.NumberOfLogicalProcessors' throws an exception (a ManagmentException with the message "Not Found") on one of the machines (but not all of them)
On Vista and higher you can use GetLogicalProcessorInformation via PInvoke to get the number of logical processor units.
On Windows XP there's no way via C# to reliably differentiate hyper-threading from other multi-processor/core configurations. The WMI solution that someone posted will class multi-core processors as hyper-threaded.
Prior to Vista the only reliable means is to check the CPUID of the processor. To use this you could create a native DLL that can be called from your managed code. The following Intel code sample would be a good starting point.
System.Environment.ProcessorCount将告诉您运行代码的计算机上存在多少个内核。
检查Environment.ProcessorCount属性,它会返回一个整数,至于HyperThreading,我不确定。
StackOverflow question 188503 has the information you need ...
Quoting the top answer on that question:
System.Environment.ProcessorCount
returns the number of logical processors (see MSDN )
To distinguish between Hyperthreaded and separate cores, sounds as though you need a bit of WMI.
GetLogicalProcessorInformation is sufficient for the HT aspect but sadly it is only available in XP SP3, 64bit XP/Vista/Server 2003 (and I believe is is slightly broken pre vista)
Joe Duffy wrapped this in c# but has not yet released the source, though Mark Russinovich has released the tool (Coreinfo) he created with it, likely you can decompile that to see the code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.