Friday, July 2, 2010

Determine CPU Usage

To read-out the CPU usage, we use the class PerformanceCounter.
With this class in general performance date can be read-out, by selecting the right parameters then also the CPU can be examined.
When using the class PerformanceCounter, the following properties have to be set to read the CPU usage:
  • CategoryName = "Processor". By doing so we set the general category for the monitoring.
  • CounterName = "% Processor Time". With this property we set the exact name of the performance indicator. 
  • InstanceName = "_Total". Catergories can be split in different instances. The category "_Total" represents always the mostly used data.
To finally get the performance data, we need the function NextValue().
For some performance data, like also in the case of the CPU usage, the function though needs a reference point to compare the current data with that, meaning the function has to be called at least twice.
Since both calls of the function have to be made with some time difference, I moved the reading of the CPU usage to an own thread, so that the run of the main application is not disturbed:
using System.Diagnostics;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        PerformanceCounter CPUCounter = new PerformanceCounter(); // instance of the class PerformanceCounter
        Thread CPUWatcher; // thread to read-out the CPU usage

        private void Form1_Load(object sender, EventArgs e)
        {
            // initialisize CPU counter with the value mentioned above
            CPUCounter.CategoryName = "Processor";
            CPUCounter.CounterName = "% Processor Time";
            CPUCounter.InstanceName = "_Total";
         
        }

        // when clicking the button, the CPU usage is determined
        private void button1_Click(object sender, EventArgs e)
        {
            // herefor the thread is (re-)initialized and started
            CPUWatcher = new Thread(new ThreadStart(GetCPUUsage));
            CPUWatcher.Start();
        }

        // the thread starts this function
        private void GetCPUUsage()
        {
            // twice the function NextValue() is called and the result displayed
            CPUCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            MessageBox.Show(CPUCounter.NextValue().ToString());
        }
    }
}

No comments:

Post a Comment