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

}

调用示例

相关推荐
ChaITSimpleLove37 分钟前
.NET9 实现排序算法(MergeSortTest 和 QuickSortTest)性能测试
算法·排序算法·.net·benchmarkdotnet·datadog.trace
一名用户3 小时前
unity实现梦日记式传送组件
后端·c#·unity3d
阿蒙Amon5 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
江山如画,佳人北望19 小时前
C#程序入门
开发语言·windows·c#
与火星的孩子对话19 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
future141219 小时前
C#每日学习日记
java·学习·c#
军训猫猫头1 天前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
追逐时光者1 天前
C#/.NET/.NET Core优秀项目和框架2025年6月简报
后端·.net
步、步、为营1 天前
.net审计库:EntityFrameworkCore.Audit
数据库·oracle·.net
ChaITSimpleLove1 天前
.NET9 实现斐波那契数列(FibonacciSequence)性能测试
.net·性能测试·斐波那契数列·fibonacci·benchmarkdotnet·datadog.trace