这是Visual Basic中的嵌套循环,循环遍历数组中的数字。
For x As Integer = 0 To test.Length - 1
Console.WriteLine(test(x))
For y As Integer = 0 To test.Length - 1
Console.WriteLine(test(x) & test(y))
Next
Next
我想通过单击按钮来终止循环。由于所有处理能力都进入循环,因此按钮显示为灰色。我该怎么办?
答案 0 :(得分:0)
您必须使用类似System.Threading.Tasks.Task
或System.ComponentModel.BackgroundWorker
的内容,并检查每次循环迭代时是否已取消任务/工作程序。多线程是一个相当广泛的主题,但this page或this page应该可以帮助您入门。
答案 1 :(得分:0)
首先添加一个布尔值
Dim done As Boolean
现在向表单添加后台工作程序。双击backgroundWorker并在backgroundWorker
下添加以下代码 Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For x As Integer = 0 To test.Length - 1
Console.WriteLine(test(x))
For y As Integer = 0 To test.Length - 1
Console.WriteLine(test(x) & test(y))
Next
If done = true then exit sub
Next
If done = true then exit sub
End Sub
现在添加一个按钮来启动循环。此按钮将布尔值设置为false并运行backgroundWorker。
Private Sub ButtonStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
done = False
BackgroundWorker1.RunWorkerAsync()
End Sub
最后添加一个按钮来停止循环。此按钮将布尔值设置为true。
Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
done = True
End SUb