Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Timers in WPF

by Ioannis Panagopoulos

There are times when you need a  task to execute periodically. There are two ways of achieving this:

  • Use the System.Windows.Threading.DispatcherTimer
  • Use the System.Threading.Timer

Say now that you want to implement a class the executes DoSomething() periodically and also informs through a delegate to whoever listens whent the execution is performed. The class for DispatcherTimer is as follows:

public class DTimer
{
    private DispatcherTimer timer;
    public event Action<int> DoSomething;
 
    private int _timesCalled = 0;
 
    public DTimer()
    {
        timer=new DispatcherTimer();
    }
    public void Start(int PeriodInSeconds)
    {
        timer.Interval = TimeSpan.FromSeconds(PeriodInSeconds);
        timer.Tick += timer_Task;
        _timesCalled = 0;
        timer.Start();
    }
 
    public void Stop()
    {
        timer.Stop();
    }
    private void timer_Task(object sender, EventArgs e)
    {
        _timesCalled++;
        DoSomething(_timesCalled);
 
    }
}

The same functionality for Timer is provided by the class below:

 

public class TTimer
{
 
    private Timer timer;
    public event Action<int> DoSomething;
    private int _timesCalled = 0;
 
    public TTimer()
    {}
    public void Start(int PeriodInSeconds)
    {
        timer = new System.Threading.Timer(timer_Task, null, 0,
        PeriodInSeconds*1000);
    }
    public void Stop()
    {
        timer.Dispose();
    }
    private void timer_Task(object State)
    {
        _timesCalled++;
        DoSomething(_timesCalled);
    }
}
Is there any difference? Well one important one is the fact that DoSomething() in the case of the DispatcherTimer is called in the same thread as the application while DoSomething() in the case of Timer is called in a new thread that was created for the timer. The two important implications of this are:
  • If DoSomething() manipulates GUI components then with the Timer you need to use: this.Dispatcher.Invoke((Action)delegate { //GUI RELATED CODE HERE} since you cannot access GUI controls from a different thread directly. With DispatcherTimer you do not need to do that.
  • If DoSomething() performas a time-consuming task, then the GUI will freeze in the case of the DispatcherTimer. In the case of the Timer it won't since the long methos is executed in a different thread

kick it on DotNetKicks.com

Shout it
blog comments powered by Disqus
hire me