VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



No CPU Load SafeSleep

by Steve Gaeke (1 Submission)
Category: VB function enhancement
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (8 Votes)

The *BEST* way to safely Sleep/Pause without taxing the CPU.

Rate No CPU Load SafeSleep


The two functions below both sleep for the specified number of seconds. However, the popular code seen in the BusySleep procedure actually causes the CPU load to stay near 100% until complete. The SafeSleep routine pauses without taxing the CPU and stays at nearly 0% CPU.
Both functions take a single value so you can sleep for fractions of a second.





Private Declare Function MsgWaitForMultipleObjects Lib "user32" (ByVal nCount As Long, pHandles As Long, ByVal fWaitAll As Long, ByVal dwMilliseconds As Long, ByVal dwWakeMask As Long) As Long


Public Sub SafeSleep(ByVal inWaitSeconds As Single)

 Const WAIT_OBJECT_0 As Long = 0

 Const WAIT_TIMEOUT As Long = &H102


 
 Dim lastTick As Single

 Dim timeout As Long

 timeout = inWaitSeconds * 1000

 lastTick = Timer


 
 Do

 Select Case MsgWaitForMultipleObjects(0, 0, False, timeout, 255)

 Case WAIT_OBJECT_0

  DoEvents

  timeout = ((inWaitSeconds) - (Timer - lastTick)) * 1000

  If timeout < 0 Then timeout = 0


 
 Case Else

  Exit Do


  
 End Select


 
 Loop While True


 
End Sub


Public Sub BusySleep(ByVal inWaitSeconds As Single)

 Dim lastTick As Single


 lastTick = Timer


 
 Do

 DoEvents


 
 Loop While (Timer - lastTick) < inWaitSeconds


 
End Sub


Download this snippet    Add to My Saved Code

No CPU Load SafeSleep Comments

No comments have been posted about No CPU Load SafeSleep. Why not be the first to post a comment about No CPU Load SafeSleep.

Post your comment

Subject:
Message:
0/1000 characters