How to Get CPU and Memory usage C#.Net
Posted by vivekcek on October 22, 2009
Ya after some long time i got chance to write an article
about,How to get CPU and Memory usage via our C#.NET.After some bit of research i found two methods are avialble,one by using WMI and System.Management class,till now i have n’t succeeded in implement the above scheme.Another simple methos avilable is using the PerformanceCounter class avilable in System.Diagnostic name space.You can find a lot of forums discussing about it also you can see that these codes show a 0% CPU use.So your are confused dont worry “Main hoon na”.
How to find the CPU usage?
1.Create a windows application in VS2005.
2.Add a timer to the Form set its interwell as 200,also set the enable property of timer true.
3.Declare an object of the performance counter class as
private PerformanceCounter cpuCounter;
.
4.Create a method InitialiseCPUCounter() and initialize cpuCounter object as shown
private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
5.On the tick event of the timer write the following code
private void updateTimer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = "CPU Usage: " +
Convert.ToInt32(cpuCounter.NextValue()).ToString() +
"%";
}
6.Dont forget to call the InitialiseCPUCounter() method from Forms constructor and also start the timer at there.
Full code is given below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; namespace WindowsApplication5 { public partial class Form1 : Form { private PerformanceCounter cpuCounter; private PerformanceCounter ramCounter; public Form1() { InitializeComponent(); InitialiseCPUCounter(); InitializeRAMCounter(); updateTimer.Start(); } private void updateTimer_Tick(object sender, EventArgs e) { this.textBox1.Text = "CPU Usage: " + Convert.ToInt32(cpuCounter.NextValue()).ToString() + "%"; this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb"; } private void Form1_Load(object sender, EventArgs e) { } private void InitialiseCPUCounter() { cpuCounter = new PerformanceCounter( "Processor", "% Processor Time", "_Total", true ); } private void InitializeRAMCounter() { ramCounter = new PerformanceCounter("Memory", "Available MBytes", true); } } }
Asharaf said
Nice. Sounds useful
Tekno Girls said
Please put your face(If possible,a full size photo). I am eagerly waiting darling..
Mohamed said
how did u add InitialiseCPUCounter();
InitializeRAMCounter(); below InitializeComponent(); ….? , when i try it didnt happen..!
Ayna said
Good one..its working
Andrius said
Timer Error… what should I do?