.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;
        };
    }

}

调用示例

相关推荐
我要打打代码1 小时前
关于C#线程 任务
开发语言·数据库·c#
Traced back1 小时前
# C# 基础语法完全指南
开发语言·c#
大黄说说2 小时前
TensorRTSharp 实战指南:用 C# 驱动 GPU,实现毫秒级 AI 推理
开发语言·人工智能·c#
芳草萋萋鹦鹉洲哦2 小时前
后端C#,最好能跨平台,桌面应用框架如何选择?
开发语言·c#
kylezhao20193 小时前
C#中开放 - 封闭原则(**Open-Closed Principle,OCP**)
服务器·c#·开闭原则
百锦再4 小时前
《C#上位机开发从门外到门内》2-7:网络通信(TCP/IP、UDP)
tcp/ip·udp·c#·嵌入式·上位机·通信·下位机
wuguan_5 小时前
C#/VP联合编程之绘制图像与保存
开发语言·c#
极客智造5 小时前
ImageSharp 实战应用指南:.NET 跨平台图像处理落地实践
图像处理·.net
时光追逐者5 小时前
一个基于 .NET + Vue 实现的通用权限管理平台(RBAC模式),前后端分离模式,开箱即用!
前端·vue.js·c#·.net·.net core
大黄说说5 小时前
在 .NET Aspire 项目中集成 AgileConfig 实现统一配置管理
.net