发布:2022/11/10 15:01:16作者:管理员 来源:本站 浏览次数:730
首先要引用 using System.Diagnostics 命名空间
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
while (true)
{
cpuCounter.NextValue();
Thread.Sleep(1000);
var cpuUsage = cpuCounter.NextValue();
string cpuUsageStr = string.Format("{0:f2} %", cpuUsage);
var ramAvailable = ramCounter.NextValue();
string ramAvaiableStr = string.Format("{0} MB", ramAvailable);
Console.WriteLine($"CPU:{cpuUsageStr} RAM:{ramAvaiableStr}");
}
若需要放到程序中运行,并且不影响程序的操作,则可以另起一个task任务,我们可以看到下方,在while循环外增加了一个Task。
注意:Task.Run方法 必须要引用.net4.5以上的框架
引用以下命名空间
using System.Threading.Tasks;
using System.Windows.Forms;
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
Task.Run(() =>
{
while (true)
{
cpuCounter.NextValue();
Thread.Sleep(1000);
var cpuUsage = cpuCounter.NextValue();
string cpuUsageStr = string.Format("{0:f2} %", cpuUsage);
var ramAvailable = ramCounter.NextValue();
string ramAvaiableStr = string.Format("{0} MB", ramAvailable);
Console.WriteLine($"CPU:{cpuUsageStr} RAM:{ramAvaiableStr}");
}
});
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4