c# 获取CPU占用率和剩余内存

c# 获取CPU占用率和剩余内存

首先要引用 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}");
                }
            });

你可能感兴趣的:(c#,c#)