tags:

views:

16131

answers:

4

I want to get the overall total CPU usage for an application in C#. I've found many ways to dig into the properties of processes, but I only want the CPU usage of the processes, and the total CPU like you get in the TaskManager.

How do I do that?

+30  A: 

You can use the PerformanceCounter class from System.Diagnostics:

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

ramCounter = new PerformanceCounter("Memory", "Available MBytes");


public string getCurrentCpuUsage(){
            cpuCounter.NextValue()+"%";
}

public string getAvailableRAM(){
            ramCounter.NextValue()+"MB";
}
CMS
+1. nice answer!
Mitch Wheat
Nice - but the original source appears to be from here:http://zamov.online.fr/EXHTML/CSharp/CSharp_927308.html
Matt Refghi
From what i discovered i had to use cpuCounter.NextValue() twice and between them i had to Sleep(500)
Shahmir Javaid
+3  A: 

CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.

Tarks
+2  A: 

You can use WMI to get CPU percentage information. You can even log into a remote computer if you have the correct permissions. Look at http://www.csharphelp.com/archives2/archive334.html to get an idea of what you can accomplish.

Also helpful might be the MSDN reference for the Win32_Process namespace: http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx

A CodeProject example: http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx

adparadox
+2  A: 

It's OK, I got it! Thanks for your help!

Here is the code to do it:

private void button1_Click(object sender, EventArgs e)
{
    selectedServer = "JS000943";
    listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}

private static int GetProcessorIdleTime(string selectedServer)
{
    try
    {
        var searcher =
           ManagementObjectSearcher
             ("\\\\"+ selectedServer +"\\root\\CIMV2",
              "SELECT * FROMWin32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");

        ManagementObjectCollection collection = searcher.Get();
        ManagementObject queryObj = collection.Cast<ManagementObject>().First();

        return Convert.ToInt32(queryObj["PercentIdleTime"]);
    }
    catch (ManagementException e)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }
    return -1;
}
xoxo