Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8354617
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T09:36:05+00:00 2026-06-09T09:36:05+00:00

I’ve been following this guide to the WPF threading model to create a little

  • 0

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));
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T09:36:07+00:00Added an answer on June 9, 2026 at 9:36 am

    There’s a few problems here. First, you are doing work on the main thread, but you’re doing it in a very roundabout way. It’s this line right here that allows your code to be responsive:

    startStopButton.Dispatcher.BeginInvoke(
        System.Windows.Threading.DispatcherPriority.SystemIdle,
        new NextCPUPeakDelegate(this.GetNextPeak));
    

    From the BeginInvoke method documentation (emphasis mine):

    Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with.

    Even though you’re sending this at a high rate, you’re queuing work on the UI thread by having the post back into the message loop occur on a background thread. This is what allows your UI to be at all responsive.

    That said, you want to restructure your GetNextPeak method like this:

    private Task GetNextPeakAsync(CancellationToken token)
    {
        // Start in a new task.
        return Task.Factory.StartNew(() => {
            // Store the counter outside of the loop.
            var cpuCounter = 
                new PerformanceCounter("Processor", "% Processor Time", "_Total");
    
            // Cycle while there is no cancellation.
            while (!token.IsCancellationRequested)
            {
                // Wait before getting the next value.
                Thread.Sleep(1000);
    
                // Get the next value.
                double currentValue = cpuCounter.NextValue();
    
                if (currentValue > thisCPUPeak)
                {
                    thisCPUPeak = currentValue;
                }
    
                // The action to perform.
                Action<double, double> a = (cv, p) => {
                    CurrentCPUPeak.Text = cv.ToString();
                    CPUPeak.Text = p.ToString();
                };
    
                startStopButton.Dispatcher.Invoke(a, 
                    new object[] { currentValue, thisCPUPeak });
            }
        }, TaskCreationOptions.LongRunning);
    }
    

    Notes about the above:

    • The call to the NextValue method on the PerformanceCounter class must have some time expire before values start coming through, as per Dylan’s answer.

    • A CancellationToken structure is used to indicate if the operation should be stopped. This drives the loop that will continuously run in the background.

    • Your method now returns a Task class which represents the background information.

    • Synchronization around the thisCPUPeak value is not needed, as the singular background thread is the only place where it is read and written to; the call to the Invoke method on the Dispatcher class has copies of the currentValue and thisCPUPeak values passed into it. If you want to access the thisCPUPeak value in any other thread (UI thread included) then you need to synchronize access to the value (most likely through the lock statement).

    Now, you’ll have to hold onto the Task on the class level as well and have a reference to a CancellationTokenSource (which produces the CancellationToken):

    private Task monitorTask = null;
    private CancellationTokenSource cancellationTokenSource = null;
    

    And then change your StartOrStop method to call the task

    private void StartOrStop(object sender, EventArgs e)
    {
        // If there is a task, then stop it.
        if (task != null)
        {
            // Dispose of the source when done.
            using (cancellationTokenSource)
            {
                // Cancel.
                cancellationTokenSource.Cancel();
            }
    
            // Set values to null.
            task = null;
            cancellationTokenSource = null;
    
            // Update UI.
            startStopButton.Content = "Resume";
        }
        else
        {
            // Update UI.
            startStopButton.Content = "Stop";
    
            // Create the cancellation token source, and
            // pass the token in when starting the task.
            cancellationTokenSource = new CancellationTokenSource();
            task = GetNextPeakAsync(cancellationTokenSource.Token);
        }
    }
    

    Note that instead of the flag, it checks to see if the Task is already running; if there is no Task then it starts up the loop, otherwise, it cancels the existing loop using the CancellationTokenSource.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
I know there's a lot of other questions out there that deal with this
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.