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

Viewed 6470

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?

3 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);

You can use something like this to get netcore process memory:

var process = Process.GetCurrentProcess();
var workingSet64 = process.WorkingSet64;
var privateMemorySize64 = process.PrivateMemorySize64;
var virtualMemorySize64 = process.VirtualMemorySize64;

And for CPU usage:

    private static DateTime? _previousCpuStartTime = null;
    private static TimeSpan? _previousTotalProcessorTime = null;

    private static double GetCpuUsageForProcess()
    {
        var currentCpuStartTime = DateTime.UtcNow;
        var currentCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;

        // If no start time set then set to now
        if (!_previousCpuStartTime.HasValue)
        {
            _previousCpuStartTime = currentCpuStartTime;
            _previousTotalProcessorTime = currentCpuUsage;
        }

        var cpuUsedMs = (currentCpuUsage - _previousTotalProcessorTime.Value).TotalMilliseconds;
        var totalMsPassed = (currentCpuStartTime - _previousCpuStartTime.Value).TotalMilliseconds;
        var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);

        // Set previous times.
        _previousCpuStartTime = currentCpuStartTime;
        _previousTotalProcessorTime = currentCpuUsage;

        return cpuUsageTotal * 100.0;
    }

I just typed in 'get all processes in c#' into google and found this:

        Process[] processlist = Process.GetProcesses();

        foreach (Process theprocess in processlist)
        {
        }

i quickly tested in asp.net core 2.2 and it works fine using System.Diagnostics; However i used windows 10 pro to test it. So i dont know if it will work with other operating systems.

Source: https://www.howtogeek.com/howto/programming/get-a-list-of-running-processes-in-c/

Related