Application.DoEvents Method |
System.Windows.Forms.Application
Application.DoEvents( )
Allows the operating system to process events and messages waiting in the message queue.
For example, you can allow a user to click a Cancel button while a processor- intensive operation is executing. In this case, without DoEvents, the click event is not processed until after the operation had completed. With DoEvents, Windows allocates time for the Cancel button's Click event to fire and the event handler to execute.
The following example uses a form with two command buttons to illustrate DoEvents. Suppose the user clicks CommandButton1. Then the Do loop in the click event executes indefinitely. However, if the user clicks CommandButton2, its click event is processed when the DoEvents statement in CommandButton1_Click is executed. This sets the Boolean flag to False , which terminates the Do loop.
Option Explicit Private lngCtr As Long Private blnFlag As Boolean Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click blnFlag = True Do While blnFlag lngCtr = lngCtr + 1 DoEvents( ) Loop MsgBox("Loop interrupted after " & lngCtr & _ " iterations.") End Sub Private Sub CommandButton2_Click( ) blnFlag = False End Sub
While DoEvents can be indispensable for increasing the responsiveness of your application, it should at the same time be used judiciously, since it entails an enormous performance penalty. For example, the following table compares the number of seconds required for a simple For...Next loop to iterate one million times when DoEvents isn't called, on the one hand, and when it's called on each iteration of the loop, on the other.
Without DoEvents | 0.01 seconds |
With DoEvents | 49.26 seconds |
If most of a procedure's processing occurs inside of a loop, one way to avoid too many calls to DoEvents is to call it conditionally every ten, hundred, or thousand iterations of the loop. For example, the following code calls DoEvents every thousand iterations:
Dim lCtr As Long For lCtr = 0 To 1000000 If (lCtr Mod 1000) = 0 Then DoEvents End If Next
DoEvents should not be used in any event procedure or callback routine that is invoked automatically by the operating system. Doing so causes re- entrance problems. (The event or routine may be called again during the processing of the DoEvents method.) For the same reason, DoEvents should not be used in in-process COM objects created with Visual Basic.
Application Class