WPF 动态模拟CPU 使用率曲线图


WPF 动态模拟CPU 使用率曲线图

     在工作中经常会遇到需要将一组数据绘制成曲线图的情况,最简单的方法是将数据导入Excel,然后使用绘图功能手动生成曲线图。但是如果基础数据频繁更改,则手动创建图形可能会变得枯燥乏味。本篇将利用DynamicDataDisplay  在WPF 中动态模拟CPU 使用率图表,实现动态生成曲线图。

     新建项目将DynamicDataDisplay.dll 加载到References 中,打开MainWindow.xaml 添加命名空间xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"。通过<d3:ChartPlotter> 创建一个图表框架,在其中添加两条整型坐标轴,X轴:<d3:HorizontalIntegerAxis>,Y轴:<d3:VerticalIntegerAxis>。<d3:Header> 用来设置图表名称,<d3:VerticalAxisTitle> 用来设置Y轴名称。

<Window x:Class="WpfPerformance.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
        Title="CPU Performance" Loaded="Window_Loaded" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="CPU Usage" Margin="20,10,0,0"
                       FontSize="15" FontWeight="Bold"/>
            <TextBlock x:Name="cpuUsageText" Margin="10,10,0,0"
                       FontSize="15"/>
        </StackPanel>
        <d3:ChartPlotter x:Name="plotter" Margin="10,10,20,10" Grid.Row="1">
            <d3:ChartPlotter.VerticalAxis>
                <d3:VerticalIntegerAxis />
            </d3:ChartPlotter.VerticalAxis>

            <d3:ChartPlotter.HorizontalAxis>
                <d3:HorizontalIntegerAxis />
            </d3:ChartPlotter.HorizontalAxis>

            <d3:Header Content="CPU Performance History"/>
            <d3:VerticalAxisTitle Content="Percentage"/>
        </d3:ChartPlotter>
    </Grid>
</Window>

XAML

      接下来工作需要通过C#每秒获取一次CPU使用率,并将这些数据生成坐标点(Point)绘制在图表中。 以下是MainWindow.xaml.cs 部分的代码内容。

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;

namespace WpfPerformance
{
    public partial class MainWindow : Window
    {
        private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
        private PerformanceCounter cpuPerformance = new PerformanceCounter();
        private DispatcherTimer timer = new DispatcherTimer();
        private int i = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void AnimatedPlot(object sender, EventArgs e)
        {
            cpuPerformance.CategoryName = "Processor";
            cpuPerformance.CounterName = "% Processor Time";
            cpuPerformance.InstanceName = "_Total";

            double x = i;
            double y = cpuPerformance.NextValue();

            Point point = new Point(x, y);
            dataSource.AppendAsync(base.Dispatcher, point);

            cpuUsageText.Text = String.Format("{0:0}%", y);
            i++;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(AnimatedPlot);
            timer.IsEnabled = true;
            plotter.Viewport.FitToView();
        }
    }
}

     通过ObservableDataSource<Point> 动态存储图表坐标点,PerformanceCounter 获取CPU使用率数值,DispatcherTimer 计时器在规定间隔进行取数操作,整型i 作为CPU使用率坐标点的X轴数值。

private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
private PerformanceCounter cpuPerformance = new PerformanceCounter();
private DispatcherTimer timer = new DispatcherTimer();
private int i = 0;

     AnimatedPlot 事件用于构造坐标点,通过设置cpuPerformance 相关参数,并使用NextValue() 方法获取当前CPU使用率数据作为Y值,整型i 作为X值。将X、Y值构造为坐标点(Point),并通过异步方式存储在dataSource 中。

private void AnimatedPlot(object sender, EventArgs e)
{
    cpuPerformance.CategoryName = "Processor";
    cpuPerformance.CounterName = "% Processor Time";
    cpuPerformance.InstanceName = "_Total";

    double x = i;
    double y = cpuPerformance.NextValue();

    Point point = new Point(x, y);
    dataSource.AppendAsync(base.Dispatcher, point);

    cpuUsageText.Text = String.Format("{0:0}%", y);
    i++;
}

     最后通过Window_Loaded 将事件加载到<Window> 中,AddLineGraph 方法将dataSource 中的坐标点绘制到图表中,曲线颜色定义为绿色,粗细设置为2,曲线名称为"Percentage"。设置计时器间隔为1秒,连续执行AnimatedPlot 事件实时绘制新坐标点。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += new EventHandler(AnimatedPlot);
    timer.IsEnabled = true;
    plotter.Viewport.FitToView();
}
CPU

鼠标右键可将图表拷贝到其他文档:

CopyPlot

动态演示

鼠标左键拖动图表浏览任意位置曲线数据,鼠标中键可以缩放显示曲线图。

Capture

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
WPF 中,可以使用 System.Diagnostics 命名空间下的 PerformanceCounter 类和 System.Windows.Threading 命名空间下的 DispatcherTimer 类来获取系统 CPU 利用率,并实现每秒更新。具体步骤如下: 1. 引入 System.Diagnostics 和 System.Windows.Threading 命名空间: ``` using System.Diagnostics; using System.Windows.Threading; ``` 2. 创建 PerformanceCounter 对象: ``` PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); ``` 其中,第一个参数 "Processor" 表示 CPU 监视器,第二个参数 "% Processor Time" 表示 CPU 使用率,第三个参数 "_Total" 表示所有 CPU 核心的总体使用率。 3. 创建 DispatcherTimer 对象: ``` DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); ``` 其中,TimeSpan.FromSeconds(1) 表示每隔 1 秒触发一次 Tick 事件。 4. 绑定 Tick 事件处理方法: ``` timer.Tick += new EventHandler(OnTimerTick); ``` 5. 实现 Tick 事件处理方法,读取并更新 CPU 使用率: ``` void OnTimerTick(object sender, EventArgs e) { float cpuUsage = cpuCounter.NextValue(); Console.WriteLine("CPU 使用率:{0}%", cpuUsage); } ``` 注意,第一次调用 NextValue 方法获取的是 0,因为需要先获取一次初始值,之后才能获取正确的 CPU 使用率。 6. 启动 Timer: ``` timer.Start(); ``` 完整示例代码如下: ``` using System; using System.Diagnostics; using System.Windows; using System.Windows.Threading; public partial class MainWindow : Window { private PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); public MainWindow() { InitializeComponent(); // 获取初始值 cpuCounter.NextValue(); // 创建 Timer DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += new EventHandler(OnTimerTick); timer.Start(); } void OnTimerTick(object sender, EventArgs e) { // 获取 CPU 使用率 float cpuUsage = cpuCounter.NextValue(); Console.WriteLine("CPU 使用率:{0}%", cpuUsage); } } ``` 注意,由于 WPF 应用程序是单线程的,因此不需要将 PerformanceCounter 对象定义为静态变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值