我试图获得与任务管理器相同的CPU使用率百分比结果。 对于内存,我使用了这段代码,看来工作正常:
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject result in results)
{
double TotalVisibleMemorySize = (Convert.ToDouble(result["TotalVisibleMemorySize"])) / (1024 * 1024);
Console.WriteLine("Total Visible Memory: {0} GB", (TotalVisibleMemorySize).ToString("0.0"));
double FreePhysicalMemory = (Convert.ToDouble(result["FreePhysicalMemory"])) / (1024 * 1024);
Console.WriteLine("Free Physical Memory: {0} GB", (FreePhysicalMemory).ToString("0.0"));
double FreePhysicalMemoryPercent = (FreePhysicalMemory * 100) / TotalVisibleMemorySize;
Console.WriteLine("Free Physical Memory: {0} %", (FreePhysicalMemoryPercent).ToString("0.0"));
double UsedPhysicalMemory = TotalVisibleMemorySize - FreePhysicalMemory;
Console.WriteLine("Used Physical Memory: {0} GB", (UsedPhysicalMemory).ToString("0.0"));
double UsedPhysicalMemorypercent = 100 - FreePhysicalMemoryPercent;
Console.WriteLine("Used Physical Memory: {0} %", (UsedPhysicalMemorypercent).ToString("0.0"));
}
因此,出于相同的想法,我尝试了CPU。我知道这个问题被问过多次,但是我没有找到正确的解决方案。
我正在使用以下代码(我也尝试过_Total):
wql = new ObjectQuery("select * from Win32_PerfFormattedData_PerfOS_Processor");
searcher = new ManagementObjectSearcher(wql);
results = searcher.Get();
foreach (ManagementObject obj in results)
{
var usage = obj["PercentProcessorTime"];
var name = obj["Name"];
Console.WriteLine(name + " : " + usage);
}
问题:此代码有什么问题,如何更正它才能起作用?还是有什么问题?
PS:我在m_procTimer_Tick事件中使用了这两个代码段,并将计时器设置为1000。