当前位置: 首页 > news >正文

WPF 监控CPU、内存性能

本段代码是一个封装的用户控件
在这里插入图片描述

<UserControl x:Class="YF_Frame.PerformanceMonitor"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" ><lvc:CartesianChart Series="{Binding SeriesCollection}" LegendLocation="Right" Background="{DynamicResource BackgroundBrush}" Foreground="{DynamicResource TextBrush}"><lvc:CartesianChart.AxisY><lvc:Axis Title="使用率 (%)" LabelFormatter="{Binding YFormatter}" MinValue="0" MaxValue="100" Foreground="{DynamicResource TextBrush}"></lvc:Axis></lvc:CartesianChart.AxisY><lvc:CartesianChart.AxisX><lvc:Axis Title="时间" Labels="{Binding Labels}" Foreground="{DynamicResource TextBrush}"></lvc:Axis></lvc:CartesianChart.AxisX></lvc:CartesianChart>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using LiveCharts;
using System.Management;
using System.Diagnostics;
using System.Windows.Threading;
using System.ComponentModel;namespace YF_Frame
{/// <summary>/// PerformanceMonitor.xaml 的交互逻辑/// </summary>public partial class PerformanceMonitor : UserControl, INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged(string propertyName = null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}public SeriesCollection SeriesCollection { get; set; }public string[] Labels { get; set; }public Func<double, string> YFormatter { get; set; }private PerformanceCounter cpuCounter;private PerformanceCounter ramCounter;public PerformanceMonitor(){InitializeComponent();SeriesCollection = new SeriesCollection{new LineSeries{Title = "CPU",Values = new ChartValues<ObservableValue>{new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0)},PointGeometry = DefaultGeometries.Circle,PointGeometrySize = 10},new LineSeries{Title = "内存",Values = new ChartValues<ObservableValue>{new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0),new ObservableValue(0)},PointGeometry = DefaultGeometries.Square,PointGeometrySize = 10}}; Labels = new[] { "1分钟前", "50秒前", "40秒前", "30秒前", "20秒前", "现在" };YFormatter = value => value.ToString("N0");DataContext = this;// 初始化CPU计数器(全局CPU使用率)cpuCounter = new PerformanceCounter("Processor",         // 类别(处理器)"% Processor Time",  // 计数器名称(CPU时间百分比)"_Total"             // 实例名称(_Total表示所有核心));// 初始化内存计数器(可用内存百分比)ramCounter = new PerformanceCounter("Memory",           // 类别(内存)"Available MBytes"   // 计数器名称(可用内存MB));// 启动定时器刷新数据(每1秒更新一次)DispatcherTimer timer = new DispatcherTimer();timer.Interval = TimeSpan.FromSeconds(5);timer.Tick += UpdatePerformanceData;timer.Start();}private void UpdatePerformanceData(object sender, EventArgs e){try{// 获取CPU使用率(取当前值)float cpuUsage = cpuCounter.NextValue();// 获取可用内存(MB)float availableMemoryMB = ramCounter.NextValue();// 计算已用内存(假设总内存16GB,你可以替换为实际值)float totalMemoryMB = 16 * 1024; // 16GB = 16 * 1024 MBfloat usedMemoryMB = totalMemoryMB - availableMemoryMB;float memoryUsagePercent = (usedMemoryMB / totalMemoryMB) * 100;// 更新图表数据UpdateChartData(cpuUsage, memoryUsagePercent);// 更新标签(可选:显示最新数据)Labels = new[] { "25秒前", "20秒前", "15秒前", "10秒前", "5秒前", "现在" };OnPropertyChanged(nameof(Labels)); // 通知UI更新}catch (Exception ex){// 由于 Windows 性能计数器损坏 => cmd lodctr / R}}private void UpdateChartData(float cpuUsage, float memoryUsage){// 获取当前CPU和内存的数据序列var cpuSeries = SeriesCollection[0].Values as ChartValues<ObservableValue>;var memorySeries = SeriesCollection[1].Values as ChartValues<ObservableValue>;// 移除最旧的数据点(保持6个数据点)if (cpuSeries.Count >= 6){cpuSeries.RemoveAt(0);memorySeries.RemoveAt(0);}// 添加新的数据点cpuSeries.Add(new ObservableValue(cpuUsage));memorySeries.Add(new ObservableValue(memoryUsage));}}
}
http://www.lryc.cn/news/621782.html

相关文章:

  • 物联网(IoT)系统中,通信协议如何选择
  • linux下找到指定目录下最新日期log文件
  • Webapi发布后IIS超时(.net8.0)
  • 【微服务】.NET8对接ElasticSearch
  • 华为实验综合小练习
  • 从源码到可执行文件:hello.c 的二进制之旅
  • Python从入门到高手9.3节: 利用字典进行格式化
  • GoLand深度解析:智能开发利器与cpolar内网穿透方案的协同实践
  • 配置国内加速源后仍然无法拉取镜像
  • Vue2与Vue3生命周期函数全面解析:从入门到精通
  • 【自动驾驶】自动驾驶概述 ② ( 自动驾驶技术路径 | L0 ~ L5 级别自动驾驶 )
  • Linux软件编程(五)(exec 函数族、system、线程)
  • Unity导航寻路轨迹可视化实现
  • Unity_数据持久化_Json
  • Ubuntu DNS 综合配置与排查指南
  • 小程序上拉加载下一页数据
  • 基于HTML5与Tailwind CSS的现代运势抽签系统技术解析
  • GEO入门:什么是生成式引擎优化?它与SEO的根本区别在哪里?
  • 流处理、实时分析与RAG驱动的Python ETL框架:构建智能数据管道(中)
  • Fanuc机器人EtherCAT通讯配置详解
  • 【Linux基础知识系列】第九十六篇 - 使用history命令管理命令历史
  • 【机器人】人形机器人“百机大战”:2025年产业革命的烽火与技术前沿
  • Zabbix【部署 01】Zabbix企业级分布式监控系统部署配置使用实例(在线安装及问题处理)程序安装+数据库初始+前端配置+服务启动+Web登录
  • 在 Vue2 中使用 pdf.js + pdf-lib 实现 PDF 预览、手写签名、文字批注与高保真导出
  • 力扣习题:基本计算器
  • Spring 工具类:StopWatch
  • Java 泛型类型擦除
  • 【递归、搜索与回溯算法】DFS解决FloodFill算法
  • Pytest项目_day17(随机测试数据)
  • JUC学习笔记-----LongAdder