如何使用.NET CORE获取C#Web应用程序中的当前CPU/RAM/磁盘使用情况? [英] How to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?
问题描述
我目前正在寻找一种使用.NET CORE在C#Web应用程序中获取当前CPU/RAM/磁盘使用率的方法.
I am currently looking for a way to get the current CPU/RAM/Disk usage in a C# web application using .NET CORE.
对于CPU和ram的使用,我使用System.Diagnostics中的PerformanceCounter类. 这些是代码:
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";
}
对于磁盘使用情况,我使用DriveInfo类.这些是代码:
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);
}
}
}
不幸的是,.NET Core不支持DriveInfo和PerformanceCounter类,因此上面的代码不起作用.
Unfortunately .NET Core does not support DriveInfo and PerformanceCounter classes, hence the codes above do not work.
有人知道我如何使用.NET CORE在C#Web应用程序中获得当前的CPU/RAM/磁盘使用率吗?
Does anyone know how I can get the current CPU/RAM/Disk usage in a C# web application using .NET CORE?
推荐答案
可通过System.Diagnostics
获得处理器信息:
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);
通过添加System.IO.FileSystem.DriveInfo
软件包,
DriveInfo
可用于Core.
DriveInfo
is available for Core by adding the System.IO.FileSystem.DriveInfo
package
这篇关于如何使用.NET CORE获取C#Web应用程序中的当前CPU/RAM/磁盘使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!