Freigeben über


Application.DoEvents

While doing the Vista Test Pass, I noticed a lot of timing and synchronization issues in the tests, and they have a lot to do with Application.DoEvents, which allows your application to handle other events that might be raised while your code runs. It processes all messages in the queue until it has run out of messages, then returns. Usually, if you set a value but the UI doesn't update, then Application.DoEvents is used to force the update. 

For example, in a form with a button and a textbox:

        private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
textBox1.Text = i.ToString();
System.Threading.Thread.Sleep(200);
//Application.DoEvents();
}
}

Without Application.DoEvents, after clicking on the button, nothing happens for two seconds, then the integer 9 appears on the textbox. With Application.DoEvents, the textbox will have an integer counting up from 0 to 9.

In her blog, Jessica talks about the dangers of Application.DoEvents.