I've been following this guide to the WPF threading model to create a little application that will monitor and display current and peak CPU usage. However, when I update my current and peak CPU in the event handler, the numbers in my window don't change at all. When debugging, I can see that the text fields do change but don't update in the window.
I've heard it's bad practice to go about building an application like this and should go for a MVVM approach instead. In fact, a few have been surprised that I've been able to run this without a runtime exception. Regardless, I'd like to figure out the code example/guide from the first link.
Let me know what your thoughts are!
And here is my xaml:
<Window x:Class="UsagePeak2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CPU Peak" Height="75" Width="260">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
<Button Content="Start"
Click="StartOrStop"
Name="startStopButton"
Margin="5,0,5,0"
/>
<TextBlock Margin="10,5,0,0">Peak:</TextBlock>
<TextBlock Name="CPUPeak" Margin="4,5,0,0">0</TextBlock>
<TextBlock Margin="10,5,0,0">Current:</TextBlock>
<TextBlock Name="CurrentCPUPeak" Margin="4,5,0,0">0</TextBlock>
</StackPanel>
Here is my Code
public partial class MainWindow : Window
{
public delegate void NextCPUPeakDelegate();
double thisCPUPeak = 0;
private bool continueCalculating = false;
PerformanceCounter cpuCounter;
public MainWindow() : base()
{
InitializeComponent();
}
private void StartOrStop(object sender, EventArgs e)
{
if (continueCalculating)
{
continueCalculating = false;
startStopButton.Content = "Resume";
}
else
{
continueCalculating = true;
startStopButton.Content = "Stop";
startStopButton.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new NextCPUPeakDelegate(GetNextPeak));
//GetNextPeak();
}
}
private void GetNextPeak()
{
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
double currentValue = cpuCounter.NextValue();
CurrentCPUPeak.Text = Convert.ToDouble(currentValue).ToString();
if (currentValue > thisCPUPeak)
{
thisCPUPeak = currentValue;
CPUPeak.Text = thisCPUPeak.ToString();
}
if (continueCalculating)
{
startStopButton.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.SystemIdle,
new NextCPUPeakDelegate(this.GetNextPeak));
}
}
}