vb.net 避免 无线循环 无限递归
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static cpu As Integer
Try
If PfmcCounter.NextValue > 90 Then
cpu += 1
Else
cpu = 0
End If
If cpu = 120 Then
kill()
For z = 1 To 100 '等待dfile进程完毕
Application.DoEvents()
System.Threading.Thread.Sleep(100)
Next
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\data\" & "long.log", ex.ToString & vbCrLf, True)
End Try
End Sub
执行这段代码的时候,如果长时间条件不满足
If PfmcCounter.NextValue > 90 Then
这里就会提示
“System.StackOverflowException”类型的未经处理的异常在 System.dll 中发生
确保您没有无线循环或无限递归
可问题是我确实需要他无限循环的执行下去啊!
[解决办法]
Application.DoEvents()
这个函数会处理没有处理的消息。
如果此时定时器到时,又会触发Timer1_Tick
如此反复,自然无限递归。
解决方法是在Timer1_Tick开头和结尾分别禁用和启用定时器。
[解决办法]
timer执行时
Timer1的enable=false;
....
....
....
Timer1的enable=true;
[解决办法]
If cpu = 120 Then
Timer1.Enable = False '只要在这里停止,以后不需要了'
kill()
[解决办法]
就是防重入标志,在合适的地方打断调用。
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static cpu As Integer
Static isBusy As Boolean
Try
If PfmcCounter.NextValue > 90 Then
cpu += 1
Else
cpu = 0 'NextValue > 90 后会不会再变小,导致重新计数?'
End If
If isBusy Then Exit Sub '防重入。不清楚你的计数规则,放这里还是放开始你自己考虑。'
If cpu = 120 Then
isBusy = True
kill()
For z = 1 To 100
Application.DoEvents()
System.Threading.Thread.Sleep(100)
Next
isBusy = False
cpu = 0 'kill 成功后是否要重置计数,还是 NextValue 会自动变小?'
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\data\" & "long.log", ex.ToString & vbCrLf, True)
End Try
End Sub