我一直在遵循WPF 线程模型指南来创建一个小应用程序,该应用程序将监视和显示当前和峰值 CPU 使用率。但是,当我在事件处理程序中更新我的当前 CPU 和峰值 CPU 时,我的窗口中的数字根本不会改变。调试时,我可以看到文本字段确实发生了变化,但在窗口中没有更新。
我听说构建这样的应用程序是不好的做法,应该改用 MVVM 方法。事实上,一些人对我能够在没有运行时异常的情况下运行它感到惊讶。无论如何,我想从第一个链接中找出代码示例/指南。
让我知道你的想法是什么!
这是我的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>
这是我的代码
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));
}
}
}