sharp12345
sharp12345

Reputation: 4498

Messagebox not blocking events on a windows.forms

I have this code:

    private void timer1_Tick(object sender, EventArgs e)
    {
        MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString());
    }

the timer is enabled, with interval = 100.

This result in an infinite number of message boxes to appear over each other, when I was expecting them to simply BLOCK the next event until the current messagebox is closed.

In more complicated applications this could lead to unpreditable results, and its as if more than 1 thread have access to the same function, but actually it is the same thread.

Why is this happening ?

Upvotes: 1

Views: 1529

Answers (2)

Lloyd
Lloyd

Reputation: 29668

It is happening exactly how it should. The tick event is powered by the message loop (unless you're using a threaded variant) and will be called repeatedly unless you block the message loop in some way (think Thread.Sleep or non message based code execution).

The message box doesn't block, it's just another window and as long as the message pump of the application is functioning so will the window, and so as each tick happens new dialogs can be created and stacked up.

A quick solution to this is something like:

private void timer1_Tick(object sender, EventArgs e)
{
    timer1.Stop();
    MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString());
    timer1.Start();
}

This would stop the timer, show a dialog and allow the timer to recover after the dialog is closed. This means you'd only get the one dialog and not a perpetual stack of them.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613592

The message box is a modal dialog which pumps the message queue. And so that allows for the timer tick messages to fire, since they are posted to the GUI thread's message queue.

This is always the case for a modal dialog that is shown in the GUI thread. Since each thread has only one message queue, the modal dialog's message pump will pull of the timer tick messages.

Upvotes: 4

Related Questions