How to get the CPU Usage in C#?

后端 未结 10 1951
醉酒成梦
醉酒成梦 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 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().First();
    
            return Convert.ToInt32(queryObj["PercentIdleTime"]);
        }
        catch (ManagementException e)
        {
            MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
        }
        return -1;
    }
    

提交回复
热议问题