Why DoEvents is Evil

From HashVB
Revision as of 21:07, 13 October 2005 by 213.224.111.244 (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

It is common in programming to need to have a timer of some form that will freeze your routine for a specified amount of time. One way to do this is to use the Sleep() API. Unfortunately there is a downside to this method, and that is that it will freeze your process. Not only does this mean that your APP's GUI updates will not occur until AFTER Sleep() returns, but also that your app will appear frozen to task manager.

So what's the solution? Why, create your own Sleep() function of course!

 Private Declare Function GetTickCount& Lib "kernel32" ()
 Private Declare Sub APISleep Alias "Sleep" Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
 Private Sub Sleep(ByVal dwMilliseconds As Long)
     Dim initTickCount As Long
     
     initTickCount = GetTickCount
     Do Until GetTickCount - initTickCount >= dwMilliseconds
         APISleep 10
         'Use the API call for sleep to prevent 100% cpu usage
         DoEvents
     Loop
 End Sub

This will freeze the routine from which it was called for the specified time, but leave the process free to update the GUI.