Monday, June 14, 2010

Calculate memory and CPU usage by using C#.NET

This sample code shows to find the RAM (memory) usage and CPU usage of a computer. This method is very usefull in order to monitor the system and particulary the amount of the available RAM in MB (MegaBytes) and the cpu usage in percents.


// Page Level declaration
protected System.Diagnostics.PerformanceCounter cpuCounter;
protected System.Diagnostics.PerformanceCounter ramCounter;

// Put into page load
cpuCounter = new System.Diagnostics.PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");

// Call this method every time you need to know the current cpu usage.
public string getCurrentCpuUsage()
{
return cpuCounter.NextValue()+"%";
}

// Call this method every time you need to get the amount of the available RAM in Mb
public string getAvailableRAM()
{
return ramCounter.NextValue() + "Mb";
}

// Put this code into button click event
textBox3.Text = getCurrentCpuUsage();
textBox4.Text = getAvailableRAM();

1 comment: