Skip to main content
 首页 » 编程设计

c#-4.0之C#之如何获取 cpu、内存和磁盘使用率(如任务管理器中所示)

2024年06月20日72xxx_UU

这些参数可以在任务管理器中看到。

请您参考如下方法:

答案可能有点大,但它会回答除磁盘使用部分之外的整个问题。

获取 CPU 利用率百分比(%)

不确定 WMI 是否可以用于这种情况,但我不想使用 WMI,因为并非所有计算机都支持 WMI。I将尝试使用其他类(例如 PerformanceCounter 等)作为解决方案。下面是一个示例代码,它将返回 CPU 利用率(以 %

为单位)
public FinalResult as float; 
public async void GetCPUCounter() 
{ 
CounterSample firstValue = cpuCounter.NextSample(); 
await Task.Delay(900); //delay is required because first  call will always return 0 
CounterSample secondValue = cpuCounter.NextSample(); 
FinalResult = CounterSample.Calculate(firstValue, secondValue); 
await Task.Delay(900); 
GetCPUCounter(); //calling again to get repeated values 
} 

现在,只需使用 Windows.Forms.Timer 重复获取 CPU 利用率。在此之前,只需从代码中的任何位置调用 GetCPUCounter() 一次即可,让我们从 Form_load 事件说:

 private void Form_load(...) 
 { 
  GetCPUCounter(); 
 } 
 private void mytimer_Tick(....) 
 { 
  string cpuUsage =  finalresult.ToString() + "%" 
 } 

获取内存利用率百分比(%)

这是一个包含 2 个async 方法的完整类,它们将返回内存使用情况和总内存:

using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 
using Microsoft.VisualBasic.Devices; 
 
public class Memory 
{ 
public int TotalRamInMb; 
public int TotalRamInGb; 
public double UsedRam; 
public int UsedRamPercentage; 
public string GetTotalRam() 
{ 
    var CI = new ComputerInfo(); 
    var mem = ulong.Parse(CI.TotalPhysicalMemory.ToString()); 
    int Mb = Convert.ToInt16(mem / (double)(1024 * 1024)); 
    TotalRamInMb = Mb; 
    if (Mb.ToString().Length <= 3) 
        return Mb.ToString() + " MB physical memory"; 
    else 
    { 
        return (Convert.ToInt16(Mb / (double)1024)).ToString() + " GB physical memory"; 
        TotalRamInGb = Convert.ToInt16(Mb / (double)1024); 
    } 
} 
public async void GetUsedRam() 
{ 
    double URam; 
    Process[] allProc = Process.GetProcesses(); 
    foreach (var proc in allProc) 
        URam += ((proc.PrivateMemorySize64) / (double)(1024 * 1024)); 
    UsedRam = URam; 
    UsedRamPercentage = (UsedRam * 100) / TotalRamInMb; 
    await Task.Delay(900); 
    GetUsedRam(); 
} 
} 

UsedRamUsedRamPercentageTotalRamInMb 等变量中获取值...并确保调用 GetUsedRam() 就像我们对 GetCPUCounter 所做的那样,然后使用 Forms.Timer 重复从上述变量中​​获取值。

我将很快通过添加磁盘使用检索过程来更新答案。干杯!