2

I have this windows form, timer1 is enabled and it's interval is set to 2000 ms. why the form shows a message box every 2 second? I mean when the first time timer tick called the UI thread will wait until the OK button pressed, so if I don't push the button so there should not another message box appear. but it appears! why?

I know that timer works on it's own thread, and the timer invokes the timer_tick function on it's intervals, the question is how another messagebox is shown when UI thread is blocked on mbox.show()?

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

    private void timer1_Tick(object sender, EventArgs e)
    {
      MessageBox.Show("test");
    }
  }
HPT
  • 351
  • 2
  • 11

4 Answers4

3

This is because you used MessageBox. It is a modal dialog that pumps a message loop. So all the normal Windows notifications are still delivered. Like paint events. The only thing it blocks is user input notifications, mouse and keyboard. But not a timer message. The Form.ShowDialog() method works this way as well.

You will have to disable the timer yourself.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2

Timer creates own worker thread which is not wait for OK button as it does main UI thread.

Try out following, does it work? (can't check it now sorry)

private void timer1_Tick(object sender, EventArgs e)     
{       
    timer.Stop();
    MessageBox.Show("test");     
    timer.Start();
}

EDIT: Answering to the question in comments

so if main UI thread stopped at mbox.Show() why another messagebox displayed?

See this SO post

MessageBox.Show will show UI on the thread it is called from. If there isn't already a message pump running on the thread it will setup a temporary one in order to function. It will tear it down after the Show call completes

Community
  • 1
  • 1
sll
  • 61,540
  • 22
  • 104
  • 156
0

The timer works on it's own thread not on the UI thread so it is not blocked by the message box dialogue.

You could have a look using reflector to see how it works.

Void
  • 265
  • 1
  • 3
  • 11
  • I know that timer works on it's own thread, and the timer invokes the timer_tick function on it's intervals, the question is how another messagebox is shown when UI thread is blocked on mbox.show()? – HPT Mar 06 '12 at 12:23
0

You will need to stop the timer when the message box is shown and restart it when the box closes:

private void timer1_Tick(object sender, EventArgs e)
{
    this.timer.Stop();
    DialogResult result = MessageBox.Show("test");
    if (result == DialogResult.OK)
    {
        this.timer.Start();
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325