How to get the CPU Usage in C#?

后端 未结 10 1983
醉酒成梦
醉酒成梦 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:11

    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.

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

    I did not like having to add in the 1 second stall to all of the PerformanceCounter solutions. Instead I chose to use a WMI solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a PerformanceCounter. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.

    I started with the snippet from here Returning CPU usage in WMI using C# and added a full explanation of the solution on my blog post below:

    Get CPU Usage Across All Cores In C# Using WMI

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

    A little more than was requsted but I use the extra timer code to track and alert if CPU usage is 90% or higher for a sustained period of 1 minute or longer.

    public class Form1
    {
    
        int totalHits = 0;
    
        public object getCPUCounter()
        {
    
            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
    
                         // will always start at 0
            dynamic firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
                        // now matches task manager reading
            dynamic secondValue = cpuCounter.NextValue();
    
            return secondValue;
    
        }
    
    
        private void Timer1_Tick(Object sender, EventArgs e)
        {
            int cpuPercent = (int)getCPUCounter();
            if (cpuPercent >= 90)
            {
                totalHits = totalHits + 1;
                if (totalHits == 60)
                {
                    Interaction.MsgBox("ALERT 90% usage for 1 minute");
                    totalHits = 0;
                }                        
            }
            else
            {
                totalHits = 0;
            }
            Label1.Text = cpuPercent + " % CPU";
            //Label2.Text = getRAMCounter() + " RAM Free";
            Label3.Text = totalHits + " seconds over 20% usage";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:20

    This class automatically polls the counter every 1 seconds and is also thread safe:

    public class ProcessorUsage
    {
        const float sampleFrequencyMillis = 1000;
    
        protected object syncLock = new object();
        protected PerformanceCounter counter;
        protected float lastSample;
        protected DateTime lastSampleTime;
    
        /// <summary>
        /// 
        /// </summary>
        public ProcessorUsage()
        {
            this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
        }
    
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public float GetCurrentValue()
        {
            if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
            {
                lock (syncLock)
                {
                    if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
                    {
                        lastSample = counter.NextValue();
                        lastSampleTime = DateTime.UtcNow;
                    }
                }
            }
    
            return lastSample;
        }
    }
    
    0 讨论(0)
提交回复
热议问题