使用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++;
    }
}
原文地址:https://www.cnblogs.com/sexintercourse/p/7110017.html