Application.DoEvents Method


Application.DoEvents Method

Class

System.Windows.Forms.Application

Syntax

     Application.DoEvents(  ) 

Description

The DoEvents method allows the application to process events and messages waiting in its message queue. Some processor-intensive activities in your application may prevent user-related input and output events from occurring in a timely manner. The DoEvents method processes pending events.

Usage at a Glance

  • While DoEvents can be indispensable for increasing the responsiveness of your application, its use should be limited, since it significantly impacts performance. For example, here are the results of a test that counted the number of seconds required to iterate a simple For...Next loop one million times, with and without an included DoEvents method call.

         Without DoEvents       0.01 seconds     With DoEvents          49.26 seconds 

  • If most of a procedure's processing occurs inside of a processor-intensive loop, one way to avoid too many calls to DoEvents is to call it conditionally every 10, 100, or 1000 iterations. The following code calls DoEvents once for every 1000 iterations:

         Dim soFar As Long = 0     For soFar = 1 To 1000000        If ((soFar Mod 1000) = 0) Then DoEvents     Next soFar 

  • Calling DoEvents from within event calls may cause pseudo-recursion issues, as the event handler may be called again due to a separate message in the message queue.

Example

The following example demonstrates the usefulness of the DoEvents method. When the GetBusy command button is clicked, it begins a very busy and infinite process. Normally, clicks on the TakeABreak command button would be blocked by the activity, but the DoEvents method makes its use possible.

     ' ----- Assumes a form with two buttons, GetBusy and TakeABreak.     Private iterationsSoFar As Long     Private interruptFlag As Boolean     Private Sub GetBusy_Click(ByVal sender As System.Object, _           ByVal e As System.EventArgs) Handles GetBusy.Click        interruptFlag = False        Do While (interruptFlag = False)           iterationsSoFar += 1           DoEvents(  )        Loop        MsgBox("Loop interrupted after " & iterationsSoFar & _           " iterations.")     End Sub     Private Sub TakeABreak_Click(ByVal sender As System.Object, _           ByVal e As System.EventArgs) Handles TakeABreak.Click        ' ----- Stop the work.        interruptFlag = True     End Sub 

Version Differences

Visual Basic 2005 adds an equivalent My.Application.DoEvents method.

See Also

Application Class




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net