How to get the CPU Usage in C#?

后端 未结 10 2153
醉酒成梦
醉酒成梦 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: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;
    
        /// 
        /// 
        /// 
        public ProcessorUsage()
        {
            this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
        }
    
        /// 
        /// 
        /// 
        /// 
        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;
        }
    }
    

提交回复
热议问题