I want to use Dynamic Data Display library to display the CPU performance with WPF.
Here is the code.
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();
}
}
}
The result likes the image below.
However the code is for one cpu only. For the modern machine, the machine has many cores. What I want is to display the cores performance.
So my idea is to use tasks to handle cores.
private PerformanceCounter[] cpuPerformance = new PerformanceCounter[System.Environment.ProcessorCount];
For each core, I want to use a task to do the performance show. The updated code is
public partial class MainWindow : Window
{
//private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
private PerformanceCounter[] cpuPerformance = new PerformanceCounter[System.Environment.ProcessorCount];
private DispatcherTimer timer = new DispatcherTimer();
private int i = 0;
public MainWindow()
{
InitializeComponent();
}
private async void AnimatedPlot(object sender, EventArgs e)
{
var t = new Task[cpuPerformance.Length];
for (int j = 0; j < cpuPerformance.Length; j++)
{
t[j] = new Task(() =>
{
ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
plotter.AddLineGraph(dataSource, Colors.Green, j+1, "Percentage");
cpuPerformance[j] = new PerformanceCounter("Processor", "% Processor Time", j.ToString());
double x = i;
double y = cpuPerformance[j].NextValue();
Point point = new Point(x, y);
dataSource.AppendAsync(base.Dispatcher, point);
cpuUsageText.Text = String.Format("{0:0}%", y);
i++;
}
);
}
await Task.WhenAll(t);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(AnimatedPlot);
timer.IsEnabled = true;
plotter.Viewport.FitToView();
}
}
But I get nothing to display. Help me to figure out what is wrong.