使用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++; } }