Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?

I am currently looking for a way to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE.

For CPU and ram usage, I use PerformanceCounter Class from System.Diagnostics. These are the codes:

 PerformanceCounter cpuCounter;
 PerformanceCounter ramCounter;

 cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

ramCounter = new PerformanceCounter("Memory", "Available MBytes");


public string getCurrentCpuUsage(){
        cpuCounter.NextValue()+"%";
}

public string getAvailableRAM(){
        ramCounter.NextValue()+"MB";
}

For disk usage, I use the DriveInfo class. These are the codes:

 using System;
 using System.IO;

 class Info {
 public static void Main() {
    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in drives) {
        //There are more attributes you can use.
        //Check the MSDN link for a complete example.
        Console.WriteLine(drive.Name);
        if (drive.IsReady) Console.WriteLine(drive.TotalSize);
    }
  }
 }

Unfortunately .NET Core does not support DriveInfo and PerformanceCounter classes, hence the codes above do not work.

Does anyone know how I can get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?

like image 772
Hardyanto Putra Antoni Avatar asked Sep 16 '16 04:09

Hardyanto Putra Antoni


People also ask

How do I check my CPU and RAM usage?

Here's is how you can check your PC's system resource usage with Task Manager. Press CTRL + Shift + Esc to open Task Manager. Click the Performance tab. This tab displays your system's RAM, CPU, GPU, and disk usage, along with network info.

How do I check my CPU Memory and disk usage Windows 10?

Using the Task ManagerPress the Windows key , type task manager, and press Enter . In the window that appears, click the Performance tab. On the Performance tab, a list of hardware devices is displayed on the left side.

How do I check my CPU storage?

Select the Start button, and then select Settings . Select System > Storage.


1 Answers

Processor information is available via System.Diagnostics:

var proc = Process.GetCurrentProcess();
var mem = proc.WorkingSet64;
var cpu = proc.TotalProcessorTime;
Console.WriteLine("My process used working set {0:n3} K of working set and CPU {1:n} msec", 
    mem / 1024.0, cpu.TotalMilliseconds);

DriveInfo is available for Core by adding the System.IO.FileSystem.DriveInfo package

like image 98
Alexey Zimarev Avatar answered Sep 19 '22 23:09

Alexey Zimarev