Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CPU Usage and Virtual Memory for a process in .Net Core?

Tags:

c#

.net-core

In .NET Core, how to get the CPU usage and Virtual Memory for a given process?

Google search result reveals that PerformanceCounter and DriverInfo class could do the job. However, PerformanceCounter & DriverInfo class are not available in .NET Core.

There is a post in stackoverflow about this question: How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?

However it only addresses: -CPU usage for the current process:

    var proc = Process.GetCurrentProcess();

I have been given process (with a ProcessID integer format). How do I get the CPU Usage and Virtual Memory for that particular process in .NET Core?

like image 875
hunterex Avatar asked Jan 14 '19 09:01

hunterex


1 Answers

You can use PerformnceCounter in the System.Diagnostics.PerformanceCounter package

for example, the next code will give you the total processor usage percent

var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
var value = cpuCounter.NextValue();
// In most cases you need to call .NextValue() twice
if (Math.Abs(value) <= 0.00)
    value = cpuCounter.NextValue();

Console.WriteLine(value);
like image 180
Wahid Bitar Avatar answered Nov 15 '22 10:11

Wahid Bitar