jester
jester

Reputation: 3489

Performance of Dispatcher timers in wpf

I have a WPF app that monitors certain processes and plots their CPU and memory utilisation into a line graph. The CPU% and memory values are read using perfomance counter class C#. The graph is again a UserControl containing a Canvas into which I am manually drawing lines according to the values fetched.

Currently I am using a Dispatcher timer in each Graph UserControl and in each tick I am getting the new values and plotting it.

The issue is as I add more and more processes to be monitored, my app eats up CPU as there are lots of updates happening.

What is a better way of achieving what I am attempting? The details of each process is in a seperate tab and is initialized only when loaded, but stopping the plot when the tab is not in view is not an option for me as I want a continuous plot.

Is there a better way of doing this?

Upvotes: 3

Views: 644

Answers (2)

GameAlchemist
GameAlchemist

Reputation: 19294

Instead of having a collection of timer that will require update, handle a collection of object needing to be polled, and a single timer that will iterate through this list on each tick.
Use a thread-safe collection (a few are provided in .Net).

Upvotes: 1

Andrej B.
Andrej B.

Reputation: 170

You can try use Reactive Extensions Timer.

private IDisposable timerSubscription;

public void StartTimer()
{
  timerSubscription = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1), Scheduler.TaskPool)
                                .ObserveOnDispatcher()
                                .Subscribe(o =>
                                  {
                                    Console.WriteLine("Hooray I'm ticking on TaskPool for {0} times!", o);
                                  }
}

/// and you can stop timer like this
public void StopTimer()
{
      using (timerSubscription)
      {

      }
}

Upvotes: 1

Related Questions