Retrieving CPU Usage in .NET

Here’s some simple and effective code to fetch CPU usage / load percentage in either ASP.NET or a .NET forms application. WIth the forms application, we’ll set it up to auto refresh every half second. You can set it to longer or shorter if you want.

Some load balancers can use a simple ASP.NET page like this that displays a server’s processor load to help decide which server to shuttle a request to. This is what I have used the simple ASP.NET implementation for.

For each of these implementations, you will need to add a reference to System.Management to your project.

ASP.NET CPU Load Percentage (C#)

using System;
using System.Management;

public partial class cputime : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ObjectQuery qry = new ObjectQuery("select * from Win32_Processor");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(qry);

        int load = 0;
        int numCpus = 0;
        foreach (ManagementObject mgmt in searcher.Get())
        {
            load += Convert.ToInt32(mgmt["LoadPercentage"]);
            numCpus++;
        }

        Response.Write(String.Format("{0}", load/numCpus));
    }
}

.NET Forms Application CPU Load Percentage (C#)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Threading;

namespace CPULoadPercentage
{
    public partial class Form1 : Form
    {
        delegate void SetTextCallback(string text);

        public Form1()
        {
            InitializeComponent();
            Thread loadThread = new Thread(new ThreadStart(outputLoad));
            loadThread.Start();
        }

        private void outputLoad()
        {
            ObjectQuery qry = new ObjectQuery("select * from Win32_Processor");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(qry);
            int load;
            int numCpus;
            while (true)
            {
                Thread.Sleep(10); //milliseconds
                load = 0;
                numCpus = 0;
                foreach (ManagementObject mgmt in searcher.Get())
                {
                    load += Convert.ToInt32(mgmt["LoadPercentage"]);
                    numCpus++;
                }
                setText(String.Format("{0}%",load / numCpus));
            }
        }

        private void setText(string text)
        {
            if (lblLoad.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(setText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                lblLoad.Text = text;
            }
        }
    }
}

If you want to change how often the label refreshes with the CPU load, just change the Thread.Sleep(10) to however many milliseconds you want between refreshes. Remember – there are 1000 milliseconds per second.

About these ads

One Comment

  1. Posted October 9, 2009 at 6:09 pm | Permalink

    please check hope this be useful for you

    http://ledomoon.blogspot.com/2009/03/using-performancecounter-class-to.html


Post a Comment

Required fields are marked *

*
*

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: