Introduction
This article describes how to measure CPU usage using C#. For this example I have used a set of defined based classes provided
by http://www.mentalis.org. You can download the supporting class
from http://www.mentalis.org/soft/class.qpx?id=12. Moreover in this example it will use
these base classes to get the CPU usage values and then it’s represented in a graphical format using
the .NET Chart
control. This will work fine with Windows
(PlatformID.Win32NT, PlatformID.Win32Windows).
Background
Sometimes there are requirements to dynamically adjust performance settings in server applications
and in order to do that we might need to calculate the CPU usage.
Basically what we do in this code is calculate the CPU usage value and represent it in a graphical format. The calculations are performed by a separate
thread.
It’s advised not to use System.Windows.Forms.Timer
but we can
use System.Threading.Timer
for more accurate results.
Using the code
Importing libraries
using System.Windows.Forms.DataVisualization.Charting;
using Org.Mentalis.Utilities;
using System.Threading;
First initialize the chart settings:
bool iscontinue = true;
private static CpuUsage cpu;
private void Form1_Load(object sender, EventArgs e)
{
this.cpuUsageChart.Series.Clear();
this.cpuUsageChart.Palette = ChartColorPalette.SeaGreen;
this.cpuUsageChart.Titles.Add("CPU Usage");
Series series = this.cpuUsageChart.Series.Add("CPU Usage");
cpuUsageChart.Series[0].ChartType = SeriesChartType.FastLine;
series.Points.Add(0);
cpuUsageChart.Series[0].YAxisType = AxisType.Primary;
cpuUsageChart.Series[0].YValueType = ChartValueType.Int32;
cpuUsageChart.Series[0].IsXValueIndexed = false;
cpuUsageChart.ResetAutoValues();
cpuUsageChart.ChartAreas[0].AxisY.Maximum =100;
cpuUsageChart.ChartAreas[0].AxisY.Minimum = 0;
cpuUsageChart.ChartAreas[0].AxisX.Enabled = AxisEnabled.False;
cpuUsageChart.ChartAreas[0].AxisY.Title = "CPU usage %";
cpuUsageChart.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
populateCPUInfo();
}
Next populate CPU information:
cpu = CpuUsage.Create();
int process = cpu.Query();
private void populateCPUInfo()
{
try
{
cpu = CpuUsage.Create();
Thread thread = new Thread(new ThreadStart(delegate()
{
try
{
while (iscontinue)
{
this.Invoke(new System.Windows.Forms.MethodInvoker(delegate()
{
int process = cpu.Query();
proVal.Text = process.ToString() + "%";
cpuUsageChart.Series[0].Points.AddY(process);
if (cpuUsageChart.Series[0].Points.Count > 40)
cpuUsageChart.Series[0].Points.RemoveAt(0);
}));
Thread.Sleep(450);
}
}
catch (Exception ex)
{
}
}));
thread.Priority = ThreadPriority.Highest;
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
We are using 450 milliseconds as interval.
Points of interest
This will only work in a Windows environment. Since CPU usage is a very rapid process, the values shown in your
Operating System and the sample application
might not tally all the time since updating the UI would consume time.