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
如此反复,自然无限递归。
解决方法是在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