.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 小时前
机器视觉中的3D高反光工件检测
人工智能·3d·c#·视觉检测
CodeCraft Studio2 小时前
文档处理控件TX Text Control系列教程:使用 .NET C# 从 PDF 文档中提取基于模板的文本
pdf·c#·.net
一念春风2 小时前
C# 背景 透明 抗锯齿 (效果完美)
开发语言·c#
且听风吟ayan2 小时前
leetcode day19 844+977
leetcode·c#
C137的本贾尼2 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#
Crazy Struggle4 小时前
.NET 使用 DeepSeek R1 开发智能 AI 客户端
人工智能·ai·.net·deepseek
CoderIsArt5 小时前
C# 中的一个特性(Attribute)[ThreadStatic]
c#
心疼你的一切5 小时前
C# 中关于补位的写法 PadLeft,PadRight 函数
开发语言·unity·c#·游戏引擎·csdn·心疼你的一切
yue0086 小时前
C#项目05-猜数字多线程
c#·多线程·猜数字·invoke·control·项目案例·methodinvoke
视觉人机器视觉6 小时前
机器视觉3D深度图颜色含义解析
人工智能·3d·c#·视觉检测