有没有办法通过。net / c#找到CPU核数?
PS:这是一个直接的代码问题,不是一个“我应该使用多线程吗?”的问题!: -)
有没有办法通过。net / c#找到CPU核数?
PS:这是一个直接的代码问题,不是一个“我应该使用多线程吗?”的问题!: -)
当前回答
看看。net是如何在内部做到这一点的,至少可以说是相当有趣的……如下图所示:
namespace System.Threading
{
using System;
using System.Runtime.CompilerServices;
internal static class PlatformHelper
{
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
private static volatile int s_lastProcessorCountRefreshTicks;
private static volatile int s_processorCount;
internal static bool IsSingleProcessor
{
get
{
return (ProcessorCount == 1);
}
}
internal static int ProcessorCount
{
get
{
int tickCount = Environment.TickCount;
int num2 = s_processorCount;
if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
{
s_processorCount = num2 = Environment.ProcessorCount;
s_lastProcessorCountRefreshTicks = tickCount;
}
return num2;
}
}
}
}
其他回答
一种选择是从注册中心读取数据。 MSDN文章主题:http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)
处理器,我相信可以在这里,HKEY_LOCAL_MACHINE\硬件\描述\系统\中央处理器
private void determineNumberOfProcessCores()
{
RegistryKey rk = Registry.LocalMachine;
String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();
textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
}
我相当肯定大多数系统上都有这个注册表项。
我想把我的0.02美元投进去。
Environment.ProcessorCount
(文档)
看看。net是如何在内部做到这一点的,至少可以说是相当有趣的……如下图所示:
namespace System.Threading
{
using System;
using System.Runtime.CompilerServices;
internal static class PlatformHelper
{
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
private static volatile int s_lastProcessorCountRefreshTicks;
private static volatile int s_processorCount;
internal static bool IsSingleProcessor
{
get
{
return (ProcessorCount == 1);
}
}
internal static int ProcessorCount
{
get
{
int tickCount = Environment.TickCount;
int num2 = s_processorCount;
if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
{
s_processorCount = num2 = Environment.ProcessorCount;
s_lastProcessorCountRefreshTicks = tickCount;
}
return num2;
}
}
}
}
我正在寻找同样的事情,但我不想安装任何nuget或服务包,所以我找到了这个解决方案,这是相当简单和直接的, 使用这个讨论,我认为运行WMIC命令并获得该值会很容易,下面是c#代码。你只需要使用系统。管理名称空间(以及用于进程等的更多标准名称空间)。
string fileName = Path.Combine(Environment.SystemDirectory, "wbem", "wmic.exe");
string arguments = @"cpu get NumberOfCores";
Process process = new Process
{
StartInfo =
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
process.Start();
StreamReader output = process.StandardOutput;
Console.WriteLine(output.ReadToEnd());
process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();
环境。ProcessorCount应该提供本地机器上的核数。