Click here to Skip to main content
15,880,608 members
Articles / Programming Languages / C# 4.0
Tip/Trick

CPU Usage with graphical indication using C# .NET

Rate me:
Please Sign up or sign in to vote.
4.80/5 (8 votes)
19 Nov 2012CPOL1 min read 61K   4.8K   35   5
CPU usage with C#.

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).  

Image 1

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

C#
using System.Windows.Forms.DataVisualization.Charting;
using Org.Mentalis.Utilities;
using System.Threading;

First initialize the chart settings:

C#
bool iscontinue = true;
private static CpuUsage cpu;

private void Form1_Load(object sender, EventArgs e)
{
    //Chart Settings 
    // Populating the data arrays.
    this.cpuUsageChart.Series.Clear();
    this.cpuUsageChart.Palette = ChartColorPalette.SeaGreen;
     
    // Set chart title.
    this.cpuUsageChart.Titles.Add("CPU Usage");

    // Add chart series
     Series series = this.cpuUsageChart.Series.Add("CPU Usage");
     cpuUsageChart.Series[0].ChartType = SeriesChartType.FastLine;

     // Add Initial Point as Zero.
    series.Points.Add(0);

    //Populating X Y Axis  Information 
    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;//Max Y 
    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:

C#
// Creates and returns a CpuUsage instance that
// can be used to query the CPU time on this operating system.
cpu = CpuUsage.Create();

int process = cpu.Query(); //Determines the current average CPU load.

private void populateCPUInfo()
{
    try
    {
        // Creates and returns a CpuUsage instance that can be
        // used to query the CPU time on this operating system.
        cpu = CpuUsage.Create();
 
        /// Creating a New Thread 
        Thread thread = new Thread(new ThreadStart(delegate()
        {
            try
            {
                while (iscontinue)
                {
                    //To Update The UI Thread we have to Invoke  it. 
                    this.Invoke(new System.Windows.Forms.MethodInvoker(delegate()
                    {
                        int process = cpu.Query(); //Determines the current average CPU load.
                        proVal.Text = process.ToString() + "%";
                        cpuUsageChart.Series[0].Points.AddY(process);//Add process to chart 

                        if (cpuUsageChart.Series[0].Points.Count > 40)
                        //clear old data point after Thrad Sleep time * 40
                            cpuUsageChart.Series[0].Points.RemoveAt(0);

                    }));

                    Thread.Sleep(450);//Thread sleep for 450 milliseconds 
                }
            }
            catch (Exception ex)
            {

            }

        }));

        thread.Priority = ThreadPriority.Highest;
        thread.IsBackground = true;
        thread.Start();//Start the Thread
    }
    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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThanks Pin
FishCommander20-Nov-12 13:36
FishCommander20-Nov-12 13:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.