如何使用.NET CORE获取C#Web应用程序当前的CPU/RAM /磁盘使用情况?
问题描述:
我目前正在寻找一种方法来使用.NET CORE在C#Web应用程序中获取当前的CPU/RAM /磁盘使用情况。如何使用.NET CORE获取C#Web应用程序当前的CPU/RAM /磁盘使用情况?
对于CPU和RAM使用情况,我使用System.Diagnostics中的PerformanceCounter类。 这些代码:
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类。这些代码:
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的核心不支持DriveInfo和的PerformanceCounter类,因此上面的代码将不会工作。
有谁知道我可以如何使用.NET CORE在C#Web应用程序中获取当前的CPU/RAM /磁盘使用情况?
答
处理器信息通过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
可用于核心加上System.IO.FileSystem.DriveInfo
包
看到这个开放的问题:https://github.com/dotnet/corefx/issues/ 9376 – thepirat000
在.NET核心中是P/Invoke吗?我并不是100%地使用coreclr,但是如果你有P/Invoke并且可以调用本机的Windows库,那么有办法做到这一点。 – Thumper