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 processes, and the total CPU like you get in the TaskManager.
How do I do that?
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 processes, and the total CPU like you get in the TaskManager.
How do I do that?
I did not like having to add in the 1 second stall to all of the
PerformanceCounter
solutions. Instead I chose to use aWMI
solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using aPerformanceCounter
. 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
It's OK, I got it! Thanks for your help!
Here is the code to do it:
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.
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.
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.
It seems to correctly measure the % of CPU being used by SQL on my 8 core server.
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#.