2016-09-16 123 views
4

我目前正在尋找一種方法來使用.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 /磁盤使用情況?

+1

看到這個開放的問題:https://github.com/dotnet/corefx/issues/ 9376 – thepirat000

+0

在.NET核心中是P/Invoke嗎?我並不是100%地使用coreclr,但是如果你有P/Invoke並且可以調用本機的Windows庫,那麼有辦法做到這一點。 – Thumper

回答

1

處理器信息通過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

相關問題