.NET使用IResourceMonitor實現獲取資源信息
寫在前面
在 Microsoft.Extensions.Diagnostics.ResourceMonitoring 包提供了一系列定制 API,專用于監(jiān)視 .NET 應用程序的資源利用率。
為了讓控制臺輸出的樣式更美觀,可以安裝一下Spectre.Console這個包
本例主要通過 IResourceMonitor 來獲取資源狀態(tài)信息,該接口支持檢索與 CPU 和內存使用情況相關的數據,并且當前與 Windows 和 Linux 平臺兼容。
示例代碼中用到的 Microsoft.Extensions.Logging 類庫也需要通過NuGet安裝一下。
代碼實現
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.ResourceMonitoring; using Microsoft.Extensions.Logging; using Spectre.Console; public class Program { public static void Main(string[] args) { var services = new ServiceCollection() .AddLogging() .AddResourceMonitoring(); var provider = services.BuildServiceProvider(); var monitor = provider.GetRequiredService<IResourceMonitor>(); _ = StartMonitoringAsync(monitor, new CancellationToken()); Console.ReadKey(); } static async Task StartMonitoringAsync(IResourceMonitor monitor, CancellationToken cancellationToken) { var table = new Table() .Centered() .Title("Resource Monitoring", new Style(foreground: Color.Purple, decoration: Decoration.Bold)) .Caption("Updates every three seconds. *GTD: Guaranteed ", new Style(decoration: Decoration.Dim)) .RoundedBorder() .BorderColor(Color.Cyan1) .AddColumns( [ new TableColumn("Time").Centered(), new TableColumn("CPU %").Centered(), new TableColumn("Memory %").Centered(), new TableColumn("Memory (bytes)").Centered(), new TableColumn("GTD / Max Memory (bytes)").Centered(), new TableColumn("GTD / Max CPU (units)").Centered(), ]); await AnsiConsole.Live(table) .StartAsync(async ctx => { var window = TimeSpan.FromSeconds(3); while (cancellationToken.IsCancellationRequested is false) { var utilization = monitor.GetUtilization(window); var resources = utilization.SystemResources; table.AddRow( [ $"{DateTime.Now:T}", $"{utilization.CpuUsedPercentage:p}", $"{utilization.MemoryUsedPercentage:p}", $"{utilization.MemoryUsedInBytes:#,#}", $"{resources.GuaranteedMemoryInBytes:#,#} / {resources.MaximumMemoryInBytes:#,#}", $"{resources.GuaranteedCpuUnits} / {resources.MaximumCpuUnits}", ]); ctx.Refresh(); await Task.Delay(window); } }); Console.CancelKeyPress += (_, e) => { e.Cancel = true; }; } }
調用示例
到此這篇關于.NET使用IResourceMonitor實現獲取資源信息的文章就介紹到這了,更多相關.NET獲取資源信息內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#?Windows?Forms中實現控件之間的連接線的方法詳解
這篇文章主要為大家詳細介紹了如何在C#?Windows?Forms應用程序中實現繪圖工具中多個控件之間的連接線功能,文中的示例代碼講解詳細,需要的可以參考下2024-02-02C# 動態(tài)輸出Dos命令執(zhí)行結果的實例(附源碼)
這篇文章主要介紹了C# 動態(tài)輸出Dos命令執(zhí)行結果的實例,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07