VB中延时CPU老是到100%有办法解决吗?
下面是函数Public Declare Function GetTickCount Lib "kernel32" () As LongPublic Function My_Delay(sSeconds As Long) '延时函数 Delay(毫秒)
Dim Begin As Long
Begin = GetTickCount
Do: DoEvents
Loop Until GetTickCount - Begin > sSeconds
End Function我的软件是会一直向数据库中请求数据,直到拿到数据结束。我是设的每1秒向数据库中查询。发现上面这个函数占用CPU很高。有办法解决吗?或者替代办法。谢谢。
下面是函数Public Declare Function GetTickCount Lib "kernel32" () As LongPublic Function My_Delay(sSeconds As Long) '延时函数 Delay(毫秒)
Dim Begin As Long
Begin = GetTickCount
Do: DoEvents
Loop Until GetTickCount - Begin > sSeconds
End Function我的软件是会一直向数据库中请求数据,直到拿到数据结束。我是设的每1秒向数据库中查询。发现上面这个函数占用CPU很高。有办法解决吗?或者替代办法。谢谢。
可以肯定是这段代码
这是毫米级的延时
计时时间长的话尽量不要这么用
可以这样使用:
Private Sub waittime(delay As Single)
Dim starttime As Single
starttime = Timer
Do Until (Timer - starttime) > delay
Loop
End Sub
还有别的办法吗
Do-Loop循环怎么做都占
泰山的意思是你用timer控件,LZ用的是程序循环
程序循环嘛,当然就是不停的取时间,比较,取时间,比较,占用100%cpu那是当然了。
用timer控件,
sub a1()
timer1时间间隔1秒
timer1允许
end sub
sub timer1_timer()
timer1禁止
调用延迟后需要允许的程序
end sub
可以使用Sleep来解决Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)该函数的意思是让当前进程挂起指定时间,此时被挂起的进程是不占用CPU资源的,但它会导致被挂起的进程假死。所以不能挂起太长时间可以把你的延迟程序修改为:Do
Sleep 50
DoEvents
Loop until Gettickcount-lngStart >lngDelay
下面的这个函数和你的类似,比较看看:
Private Declare Function timeGetTime Lib "winmm.dll" () As Long'单位为毫秒
Public Sub Delay(ByVal MS As Long)
Dim T As Long
T = timeGetTime
While timeGetTime - T < MS
DoEvents
Wend
End Sub下面再提供一个延时类,用起来好像还行,强烈推荐:
http://download.csdn.net/source/752060
Private Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Function GetTickCountEx() As Currency
Dim stTime As SYSTEMTIME
GetSystemTime stTime
GetTickCountEx = DateDiff("d", "1900-01-01", stTime.wYear & "-" & stTime.wMonth & "-" & stTime.wDay) * 8640000@ + stTime.wHour * 360000@ + stTime.wMinute * 60000@ + stTime.wSecond * 1000@ + stTime.wMilliseconds
End FunctionPublic Sub Delay(wMilliseconds As Long)
Dim cyStartTime As Currency
cyStartTime = GetTickCountEx
Do While (GetTickCountEx() - cyStartTime) < wMilliseconds
DoEvents
Sleep 1
Loop
End SubSub main()
Debug.Print Timer
Delay 5000 '延时5秒,基本上不占CPU
Debug.Print Timer
End Sub
只需要程序结构上稍做调整,原先循环中的查询改为在 Timer 事件中调用。
试试上面这个类的方法,我测试了下发现cpu变化不明显。
至于sleep多少,可以根据调试情况而定。
我以前遇到过同样的问题
加了Sleep(1)直接从100%下降到0%