投稿 评论 顶部

performancecounter使用率详解

佚名 网络安全

C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率:

先看界面:

建一个 Windows Form  桌面程序,代码如下:

复制代码

using System;using System.ComponentModel;using System.Windows.Forms;using System.Diagnostics;using System.Threading;namespace PerformanceCounterApp{    public partial class MainForm : Form    {        private BackgroundWorker backgroundWorker;        private bool isWorking = false;        public MainForm()        {            InitializeComponent();        }        private void Form_Load(object sender, EventArgs e)        {            cpuLabel.Text = string.Empty;            diskLabel.Text = string.Empty;            backgroundWorker = new BackgroundWorker();            backgroundWorker.WorkerReportsProgress = true;            backgroundWorker.WorkerSupportsCancellation = true;            backgroundWorker.DoWork += BackgroundWorker_DoWork;            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;        }        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)        {            //PerformanceCounter diskp = new PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total");            isWorking = true;            backgroundWorker.ReportProgress(0, "Loading.../");            PerformanceCounter cpup = new PerformanceCounter("Processor", "% Processor Time", "_Total");            PerformanceCounter diskp = new PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "_Total");            try            {                do                {                    Thread.Sleep(150);                    var cpuv1 = (int)cpup.NextValue();                    var diskv1 = (int)diskp.NextValue();                    Thread.Sleep(150);                    var cpuv2 = (int)cpup.NextValue();                    var diskv2 = (int)diskp.NextValue();                    Thread.Sleep(150);                    var cpuv3 = (int)cpup.NextValue();                    var diskv3 = (int)diskp.NextValue();                    Thread.Sleep(150);                    var cpuv4 = (int)cpup.NextValue();                    var diskv4 = (int)diskp.NextValue();                    var cpuv = (cpuv1 + cpuv2 + cpuv3 + cpuv4) / 4;                    var diskv = (diskv1 + diskv2+ diskv3 + diskv4) / 4;                    string data = $"{cpuv}%/{diskv}";                    backgroundWorker.ReportProgress(0,data);                } while (!backgroundWorker.CancellationPending);            }            catch (Exception)            {                throw;            }            finally            {                cpup.Dispose();                diskp.Dispose();                isWorking = false;            }        }        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)        {            string[] data = e.UserState.ToString().Split('/');            cpuLabel.Text = $"CPU: {data[0]}";            diskLabel.Text = $"Disk: {data[1]} Bytes/sec";        }        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)        {            var result = e.Result;            var cc = e.Cancelled;        }        private void startButton_Click(object sender, EventArgs e)        {            if (backgroundWorker.CancellationPending) return;            if (isWorking)            {                startButton.Text = "Start";                backgroundWorker.CancelAsync();            }            else            {                startButton.Text = "Stop";                backgroundWorker.RunWorkerAsync();            }         }        private void Form_Closed(object sender, FormClosedEventArgs e)        {            if (isWorking)            {                startButton.Enabled = false;                backgroundWorker.CancelAsync();            }        }    }}