Thursday 10 July 2014

C# CPU Usage

System.Diagnostics.PerformanceCounter cpuCounter;
protected System.Diagnostics.PerformanceCounter ramCounter;
protected void Page_Load(object sender, EventArgs e)
{
// 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");
}
protected void Button1_Click(object sender, EventArgs e)
{
// Put this code into button click
eventtextBox3.Text = getCurrentCpuUsage();
textBox4.Text = getAvailableRAM();
}
// 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";
}