Inspired by this blog. I want to plot each processor's performance. After add DynamicDataDisplay from Nuget. So the xaml code.
<Window x:Class="CPU_Performance.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
xmlns:local="clr-namespace:CPU_Performance"
mc:Ignorable="d"
Title="MainWindow" 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>And the cs code is:
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
namespace CPU_Performance
{
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(()=>
{
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)
{
plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(AnimatedPlot);
timer.IsEnabled = true;
plotter.Viewport.FitToView();
}
}
}
But it display nothing. Why? Even I moved the dataSource to the body of for loop.