0

I have a DispatcherTimer in my WPF application that updates text within the application every 200 milliseconds. The program displays a series of counters, clocks and timers.

private DispatcherTimer dispatch = new DispatcherTimer();

public Timer()
{
    InitializeComponent();
    this.dispatch.Interval = TimeSpan.FromMilliseconds(200);
    this.dispatch.Tick += new EventHandler(updateTimer);
}

private void updateTimer(object sender, EventArgs e)
{
    loadingImage.RenderTransform = new RotateTransform(counter * 36);
    counter++;

    try
    {
        clock.Text = DateTime.Now.ToString(@clockFormat.Text);
    }
    catch (Exception) { }

    try
    {
        watch.Text = watchCounter.Elapsed.ToString(@watchFormat.Text);
    }
    catch (Exception) { }
}

The problem I am having is whenever the DispatcherTimer is running, it causes a "stutter" in my application. Its as if everytime it runs the event handler, the program lags a little bit. Is there a way to get rid of this lag?

Jason Axelrod
  • 7,155
  • 10
  • 50
  • 78
  • 1
    Are those exceptions being thrown, or did you add the try-catch as a precaution? – odyss-jii Nov 08 '14 at 19:57
  • Is the timer causing the stutter or is the timer just being delayed by other parts of the UI? Consider increasing the priority of the dispatcher timer so it will run at a more consistent rate. See [this question](http://stackoverflow.com/questions/14354561/how-to-make-dispatchertimer-events-smoother-in-wpf). – Mike Zboray Nov 08 '14 at 20:55
  • @mikez if the timer has trouble keeping up then his UI thread is overloaded already. The stuttering is just a symptom of overloading. – usr Nov 08 '14 at 21:02
  • @usr It really depends on why the stutter is happening. If relatively unimportant UI work (e.g. hit testing) is getting prioritized over the timer, then upping the priority may help. However, if there really is too much high priority rendering going on, changing priority won't help. It is really easy to try changing the priority, which is why I added this. Other options like using an animation instead or "standard WPF optimization techniques" are going to take longer to implement. – Mike Zboray Nov 08 '14 at 21:35

2 Answers2

1

The timer is not causing the delay. Your code does. You are creating rendering load on the UI thread. Optimize drawing so that the element that you are animating is quick to redraw.

Also, better use an animation instead of a timer.

Also note, that timers might skew in time. Incremental computations such as counter counter are inherently unstable. Make note when your app starts and compute the counter value from the time passed.

usr
  • 168,620
  • 35
  • 240
  • 369
0

Quick search points to RotateTransform as a possible culprit. See this answer https://stackoverflow.com/a/8766252/166333 where it mentions blocking at the process level. There are some answers in there too that may work for you.

Community
  • 1
  • 1
Trevor Ash
  • 623
  • 4
  • 8