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

}

调用示例

相关推荐
csdn_aspnet3 小时前
C# 在逗号分割的字符串中判断是否包含指定字符
c#·正则·linq·string·regex·contains
宝桥南山3 小时前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
淡海水5 小时前
02-06-历史-托管GC机制-垃圾回收如何影响数据结构选择
c#·编译·gc·机器码
longxiaozhang616 小时前
C# static:静态成员,小白也能看懂
开发语言·c#
longxiaozhang616 小时前
C#继承:让代码少写一点,偷懒的好方法
开发语言·c#
rockey62717 小时前
C#脚本引擎之AScript与DynamicExpresso对比
c#·.net·script·动态脚本
Vae_Mars1 天前
C#中的delegate委托
开发语言·c#
qq_548612451 天前
.NET 平台报表工具汇总(.NET Framework /.NET6-8,中国式复杂报表、Web 嵌入、填报、导出打印)
前端·.net
公子小六1 天前
基于.NET的Windows窗体编程之WinForms音频控件
windows·microsoft·c#·.net·音视频·winforms
绿浪19841 天前
c# 结构体 能不能直接封送检测
开发语言·c#