C# WPF timer (stopwatch) with DispatcherTimer

user360330 picture user360330 · Jul 31, 2011 · Viewed 8.1k times · Source

I'm trying to make a simple stopwatch but it just doesn't work.. The app just crashes when I press the buttons. What's wrong?

public partial class MainWindow : Window
{
    private DispatcherTimer timer;

    public MainWindow()
    {
        InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, delegate
        {
            this.Show.Text = DateTime.Now.ToString("HH:mm:ss:fff");
        }, this.Dispatcher);
    }

    private void Start(object sender, RoutedEventArgs e)
    {
        timer.Start();
    }

    private void Stop(object sender, RoutedEventArgs e)
    {
            timer.Stop();
    }
}

Answer

slugster picture slugster · Jul 31, 2011

Your problem is this:

DispatcherTimer timer = ...

you have created a new instance of the timer which is scoped to your constructor. You have not set the member variable timer. This means when you hit the start button you will be trying to start a timer that has not been instantiated yet and you will get a NullReferenceException. I suggest you:

  • rename the member variable timer to _timer. This helps avoid confusion to similarly named local variables.
  • change the line DispatcherTimer timer = new DispatcherTimer to _timer = new DispatcherTimer(...