views:

352

answers:

2

Hello all,

I have a timer on a windows form (C# 3.0, .net 3.5 SP1, VS2008 SP1, Vista) that seems to work even after it is stoppped. The code is:

using System;
using System.Windows.Forms;

namespace TestTimer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            StartTimer();
        }

        private DateTime deadline;

        private void StartTimer()
        {
            deadline = DateTime.Now.AddSeconds(4);
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int secondsRemaining = (deadline - DateTime.Now).Seconds;

            if (secondsRemaining <= 0)
            {
                timer1.Stop();
                timer1.Enabled = false;
                MessageBox.Show("too slow...");
            }
            else
            {
                label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second");
            }
        }
    }
}

Even after the timer1.Stop() is called, I keep reeciving MessageBoxes on the screen. When I press esc, it stops. Howevere, I've expected that only one message box appears... What else should I do? adding timer1.Enabled = false does not change the behavior.

Thanks

+2  A: 

I could be wrong, but is MessageBox.Show() a blocking operation (that waits for you to dismiss the dialog)? If so, just move the Show() call to after the Stop/Enabled lines?

Brian
A: 

A couple of factors may be at work here.

The modal MessageBox.Show() could prevent the timer stop from taking effect until it is dismissed (as Brian pointed out).

The timer1_Tick could be executing on a background thread. UI calls such as MessageBox.Show() and background threads to not mix.

Both issues can be solved by using BeginInvoke to call a method that shows the message box.