zoukankan      html  css  js  c++  java
  • 使用WPF动态显示CPU使用率

    使用WPF动态显示CPU使用率

     开源框架  admin  9个月前 (07-14)  1337浏览

    使用WPF动态显示CPU使用率

    基于WPF的开源图表控件有很多,大多数都是静态图表,如果需要绘制CPU使用率这样的动态数据就显得力不从心,微软开源的DynamicDataDisplay控件弥补了这个不足,为了做个备忘,我用它来实时绘制CPU使用率曲线,当然,这个控件也可以绘制动态线图、气泡图和热力图,具体可参阅官网示例代码,使用方法非常简单,下面就直接贴代码,文本末尾提供VS2013的示例代码下载。

    1、首先需要在项目中引用DynamicDataDisplay.dll,该程序集可通过官网下载或者NuGet方式搜索获去,在包控制台执行以下命令即可自动引用。

    PM> Install-Package DynamicDataDisplay

    2、在XAML文件中引用D3命名空间,同时添加一个名为ChartPlotter的图表控件。

    <Window x:Class="WpfCpuUsageSample.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="MainWindow" Loaded="Window_Loaded" Height="350" Width="525">
        <Grid>
            <d3:ChartPlotter Grid.Column="0" Grid.Row="0"  Name="plotter"/>
        </Grid>
    </Window>
    

    3、在后台窗体类中申明数据源ObservableDataSource用于为图表控件提供数据,PerformanceCounter是性能计数器,可通过它来获取CPU使用率,DispatcherTimer是一个基于WPF的计时器,支持在子线程异步通知UI线程,在窗口加载事件中初始化这些类,并未计时器绑定一个处理程序,用于获取CPU使用率,并将当前的使用率加入到动态曲线中。

    public partial class MainWindow : Window
    {
        private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
        private PerformanceCounter performanceCounter = new PerformanceCounter();
        private DispatcherTimer dispatcherTimer = new DispatcherTimer();
        private int currentSecond = 0;
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
            plotter.LegendVisible = false;
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Tick += timer_Tick;
            dispatcherTimer.IsEnabled = true;
            plotter.Viewport.FitToView();
        }
    
        private void timer_Tick(object sender, EventArgs e)
        {
            performanceCounter.CategoryName = "Processor";
            performanceCounter.CounterName = "% Processor Time";
            performanceCounter.InstanceName = "_Total";
    
            double x = currentSecond;
            double y = performanceCounter.NextValue();
    
            Point point = new Point(x, y);
            dataSource.AppendAsync(base.Dispatcher, point);
    
            currentSecond++;
        }
    }
  • 相关阅读:
    【胡策篇】题目
    【学术篇】luogu3768 简单的数学题(纯口胡无代码)
    【学术篇】规律选手再次证明自己(舒老师的胡策题 T2 LX还在迷路)
    【模板篇】Link Cut Tree模板(指针)
    【学术篇】51nod 1238 最小公倍数之和
    【学术篇】2.28测试T2 线段 拓扑排序
    【学术篇】SPOJ FTOUR2 点分治
    【颓废篇】Py:从零开始的poj自动提交
    【学术篇】CF935E Fafa and Ancient Mathematics 树形dp
    安卓启动图去除顶部title和状态栏
  • 原文地址:https://www.cnblogs.com/liyancheng/p/5406574.html
Copyright © 2011-2022 走看看