Difference between revisions of "Sleep without locking"
From HashVB
Line 4: | Line 4: | ||
Private Declare Function GetTickCount& Lib "kernel32" () | Private Declare Function GetTickCount& Lib "kernel32" () | ||
− | + | Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long) | |
− | Private Sub | + | |
+ | Private Sub Sleep2(dwMilliseconds As Long) | ||
Dim initTickCount As Long | Dim initTickCount As Long | ||
initTickCount = GetTickCount | initTickCount = GetTickCount | ||
Do Until GetTickCount - initTickCount >= dwMilliseconds | Do Until GetTickCount - initTickCount >= dwMilliseconds | ||
+ | Sleep 10 | ||
+ | 'Use the API call for sleep to prevent 100% cpu usage | ||
DoEvents | DoEvents | ||
Loop | Loop |
Revision as of 21:18, 2 September 2005
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 Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Sub Sleep2(dwMilliseconds As Long) Dim initTickCount As Long initTickCount = GetTickCount Do Until GetTickCount - initTickCount >= dwMilliseconds Sleep 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.
Simple as that.