.NET 资源监视

写在前面

在 Microsoft.Extensions.Diagnostics.ResourceMonitoring 包提供了一系列定制 API,专用于监视 .NET 应用程序的资源利用率。

为了让控制台输出的样式更美观,可以安装一下Spectre.Console这个包

本例主要通过 IResourceMonitor 来获取资源状态信息,该接口支持检索与 CPU 和内存使用情况相关的数据,并且当前与 Windows 和 Linux 平台兼容。

示例代码中用到的 Microsoft.Extensions.Logging 类库也需要通过NuGet安装一下。

代码实现

cs 复制代码
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;
        };
    }

}

调用示例

相关推荐
新手unity自用笔记11 小时前
项目-坦克大战学习-子弹的移动与销毁
笔记·学习·c#
qinzechen11 小时前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
yufei-coder15 小时前
C# Windows 窗体开发基础
vscode·microsoft·c#·visual studio
dangoxiba15 小时前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
AitTech15 小时前
深入理解C#中的TimeSpan结构体:创建、访问、计算与格式化
开发语言·数据库·c#
hiyo58519 小时前
C#中虚函数和抽象函数的概念
开发语言·c#
开心工作室_kaic21 小时前
基于微信小程序的校园失物招领系统的设计与实现(论文+源码)_kaic
c语言·javascript·数据库·vue.js·c#·旅游·actionscript
时光追逐者1 天前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore
friklogff1 天前
【C#生态园】打造现代化跨平台应用:深度解析.NET桌面应用工具
开发语言·c#·.net
hiyo5852 天前
C#的面向对象
开发语言·c#