簡體   English   中英

如何使用 .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/磁盤使用情況的方法。

對於 CPU 和內存使用,我使用 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 Core 不支持 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);

通過添加System.IO.FileSystem.DriveInfo包, DriveInfo可用於 Core

您可以在System.Diagnostics.PerformanceCounter 包中使用PerformnceCounter

例如,下一個代碼將為您提供總處理器使用百分比

var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total",true);
var value = cpuCounter.NextValue();
//Note: In most cases you need to call .NextValue() twice to be able to get the real value
if (Math.Abs(value) <= 0.00)
    value = cpuCounter.NextValue();

Console.WriteLine(value);

您可以對所有操作系統注冊的性能計數器執行相同的操作。


更新:

我不確定在創建 PerformanceCounter 類的新實例后是否應該做一些事情,但有時當我獲得下一個值時,它會變為 0。

所以我決定在應用程序級別創建一個 PerformanceCounter 實例。

例如

public static class DiagnosticHelpers
{
    public static float SystemCPU { get; private set; }
    private static readonly object locker = new object();


    static DiagnosticHelpers()
    {
        SystemCPU = 0;
        Task.Run(() =>
        {
            var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
            while (true)
            {
                Thread.Sleep(1000);
                lock (locker)
                {
                    SystemCPU = cpuCounter.NextValue();
                }
            }
        });
    }
}

對於 Windows,我正在使用它

var   memorielines= GetWmicOutput("OS get FreePhysicalMemory,TotalVisibleMemorySize /Value").Split("\n");

        var freeMemory= memorielines[0].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
        var totalMemory = memorielines[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];


        var cpuLines = GetWmicOutput("CPU get Name,LoadPercentage /Value").Split("\n");


        var CpuUse = cpuLines[0].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];
        var CpuName = cpuLines[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1];



    private string GetWmicOutput(string query, bool redirectStandardOutput = true)
    {
        var info = new ProcessStartInfo("wmic");
        info.Arguments = query;
        info.RedirectStandardOutput = redirectStandardOutput;
        var output = "";
        using (var process = Process.Start(info))
        {
            output = process.StandardOutput.ReadToEnd();
        }
        return output.Trim();
    }

對於磁盤信息,您可以使用此查詢:

LOGICALDISK get Caption,DeviceID,FileSystem,FreeSpace,Size /Value

如果您想要更好的輸出格式,請查看本文: https : //www.petri.com/command-line-wmi-part-3

通過雙擊項目將此 nuget 包添加到您的項目中。

<ItemGroup>
    <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="6.0.0" />
</ItemGroup>

當您運行代碼時,您將收到如下所示的錯誤。

Performance counters cannot be initialized! System.UnauthorizedAccessException: Access to the registry key 'Global' is denied.

要解決此錯誤,您必須將應用程序池用戶添加到“性能監視器用戶”組。 以管理員模式打開命令行,然后運行此命令。

net localgroup "Performance Monitor Users" "IIS APPPOOL\MYAPPPOOL"  /add

MYAPPPOOL 將替換為您的真實應用程序池名稱。

如果iis重啟沒有解決就重啟機器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM