How to get the CPU Usage in C#?

后端 未结 10 1982
醉酒成梦
醉酒成梦 2020-11-22 06:22

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 proce

相关标签:
10条回答
  • 2020-11-22 06:54
    public int GetCpuUsage()
    {
        var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
        cpuCounter.NextValue();
        System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
        return (int)cpuCounter.NextValue();
    }
    

    Original information in this link https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/

    0 讨论(0)
  • 2020-11-22 06:55

    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.

    See also a CodeProject example How To: (Almost) Everything In WMI via C#.

    0 讨论(0)
  • 2020-11-22 07:02

    This seems to work for me, an example for waiting until the processor reaches a certain percentage

    var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    int usage = (int) cpuCounter.NextValue();
    while (usage == 0 || usage > 80)
    {
         Thread.Sleep(250);
         usage = (int)cpuCounter.NextValue();
    }
    
    0 讨论(0)
  • 2020-11-22 07:08

    After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in "sqlservr" as appName.

    private static void RunTest(string appName)
    {
        bool done = false;
        PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
        PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
        while (!done)
        {
            float t = total_cpu.NextValue();
            float p = process_cpu.NextValue();
            Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
            System.Threading.Thread.Sleep(1000);
        }
    }
    

    It seems to correctly measure the % of CPU being used by SQL on my 8 core server.

    0 讨论(0)
  • 2020-11-22 07:08

    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 = new
               ManagementObjectSearcher
                 (@"\\"+ selectedServer +@"\root\CIMV2",
                  "SELECT * FROM Win32_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;
    }
    
    0 讨论(0)
  • 2020-11-22 07:09

    You can use the PerformanceCounter class from System.Diagnostics.

    Initialize like this:

    PerformanceCounter cpuCounter;
    PerformanceCounter ramCounter;
    
    cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    

    Consume like this:

    public string getCurrentCpuUsage(){
                return cpuCounter.NextValue()+"%";
    }
    
    public string getAvailableRAM(){
                return ramCounter.NextValue()+"MB";
    } 
    
    0 讨论(0)
提交回复
热议问题