Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a subtle bug that's induced by the MessageBox.Show() call. MessageBox pumps a message loop to keep the UI alive. Which allows the Tick event handler to run again, even though it is already active from the previous tick. The counter variable doesn't get incremented until you click the OK button. As a result, the screen fills with message boxes and that won't stop until you click the OK button ten times.</p> <p>You need to increment the counter <em>before</em> showing the message box. Fix:</p> <pre><code>int counter = 0; private void timer1_Tick(object sender, EventArgs e) { counter++; if (counter &gt; 10) timer1.Enabled = false; else MessageBox.Show("Hello"); } </code></pre> <p>This kind of problem is also the reason that DoEvents() got such a bad reputation. It is pretty difficult to write code that can properly deal with the re-entrancy induced by the message loop. You need to keep boolean flags around that indicate that code is already active. Which is another way to solve your problem:</p> <pre><code>int counter = 0; bool showingBox = false; private void timer1_Tick(object sender, EventArgs e) { if (showingBox) return; showingBox = true; try { MessageBox.Show("Hello"); counter++; if (counter == 10) timer1.Enabled = false; } finally { showingBox = false; } } </code></pre> <p>You now get only one message box at a time, probably what you are really looking for.</p> <p>I should mention that this re-entrancy problem is pretty specific to timers. A dialog takes counter-measures to avoid re-entrancy problems, it disables all the windows in the application. That ensures that the user cannot do things like closing the main window or clicking a button that brings up the dialog again. Both rather disastrous mishaps. That takes care of most of the 'unexpected' Windows notifications, basically any of the messages that are generated by the user. The edge case is a timer (WM_TIMER is not disabled) whose event handler has a UI effect.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload