Blog

Filter posts by Category Or Tag of the Blog section!

Get the CPU usage of the server in C#

Monday, 28 December 2015

Recently I had a task on a project to get the overall CPU usage in a Dot Net web application. After searching and testing some codes, the following code gave me the exact result:

 

 public static int GetServerCpuUsage()

        {

            var performanceCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", "DESKTOP-VITIJ30");

            performanceCounter.NextValue();

            System.Threading.Thread.Sleep(1000);

            return (int)performanceCounter.NextValue();

        }

 

Note that the name DESKTOP-VITIJ30 is my computer name.  In most given solutions without opening a thread, the CPU usage returns 0, that's because the performanceCounter needs to be updated for at least twice and by calling a thread we can get the exact output. By the way, by using the PerformanceCounter of System.Diagnostics, you can also get the available Ram of the running machine by passing some specific parameters:

 

public static string GetAvailableRAM()

        {

            var performanceCounter = new PerformanceCounter("Memory", "Available MBytes");

            return performanceCounter.NextValue() + "MB";

        }

Category: Software

Tags: C#

comments powered by Disqus