我有这个循环打开随机文件并从这些文件中顺序读取。由于这些文件几乎可以成千上万,所以我需要一种方法来退出for和do循环,而不会像现在单击停止搜索按钮时那样挂起系统。
目前我发现使用的最佳方法是在单击停止搜索按钮时将x循环设置为最后一个数字。
我试图用exit for和exit do退出循环,但这些没有区别为什么系统在系统停止循环之前暂停一段时间。在程序响应之前,我必须在停止搜索按钮上单击几次。 下面是循环代码的一部分: -
cur.execute("""INSERT INTO database (date, id) VALUES (now(), %s );""" % (user,))
答案 0 :(得分:-1)
在做了一些进一步的研究后,我发现如果我将代码包含在一个线程中,我可以完美地停止循环(暂停线程)。
如果你按照我的方式使用线程;在加载表单时,您最好使用以下代码: -
Private Sub LaybuyInputDialog_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.CheckForIllegalCrossThreadCalls = False
End Sub
也不要忘记在表单顶部插入 Imports.System.Threading 。
为了以下新线程,我改变了代码: -
Dim thread As System.Threading.Thread
Private Sub DoSearch()
Button1.Hide()
stopsearch = False
Dim x As Single
Dim startvalue As Single
Dim endvalue As Single
startvalue = Val(TextBox1.Text)
endvalue = Val(TextBox2.Text)
If TextBox4.Text <> "" Then
ListView1.Items.Clear()
ProgressBar1.Minimum = startvalue
ProgressBar1.Maximum = endvalue
Button1.Text = "Searching . . . "
For x = startvalue To endvalue
ProgressBar1.Value = x
Dim f As String
If stopsearch = True Then
x = endvalue
Exit For
End If
f = TextBox3.Text + "-" + Trim(Str(x)) + "." + company
If File.Exists(D_Drive + "\STORE-16\" + f) Then
'MsgBox(f)
FileClose(30)
FileOpen(30, D_Drive + "\store-16\" + f, OpenMode.Input)
Try
Dim sr As String = ""
Do While Not EOF(30)
sr = LineInput(30)
If stopsearch = True Then
x = endvalue
Exit Do
End If
If InStr(UCase(sr), UCase(TextBox4.Text)) > 0 Then
Dim i As ListViewItem = ListView1.Items.Add(Str(x))
i.SubItems.Add(sr)
If ListView1.Items.Count > 0 Then
ListView1.Items(ListView1.Items.Count - 1).EnsureVisible()
End If
Application.DoEvents()
End If
Loop
Finally
FileClose(30)
End Try
End If
Next x
Button1.Text = "Re-start Search "
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
thread = New System.Threading.Thread(AddressOf DoSearch)
thread.Start()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
stopsearch = True
Try
thread.Suspend()
Catch ex As Exception
'
End Try
End Sub
希望我的回答有助于某人;如果你有更好的解决方案,请随时评论! !