vb.net - 按下按钮时停止循环

时间:2016-05-03 09:36:07

标签: vb.net loops

我有一个循环(在另一个班级中)当我按下按钮时我想要停止,但我不知道该怎么做

这是我的代码:

'My FORM

Dim blStop = False

Private Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
        AnotherClass.doTheLoop(blStop)
End Sub

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
        blStop = True
End Sub



'AnotherClass Loop

While (blStop = False)
    'blablabla
End While

2 个答案:

答案 0 :(得分:1)

你的问题是:

Public Sub doTheLoop(blStop as Boolean) 
    While (blStop = False) 
       'blablabla 
    End While 
End Sub

blStop的声明,创建一个新变量,所以当你设置值为False时,你只需要在本地设置一个decalred。

快速而肮脏的修复方法是声明布尔值ByRef - 这意味着它仍将引用原始变量。

Public Sub doTheLoop(ByRef blStop as Boolean) 
    While (blStop = False) 
       'blablabla 
    End While 
End Sub

更好的解决方案是在你的班级中设置一个方法,当你想要停止而不是传递圆形变量时,你可以调用它。

答案 1 :(得分:1)

以下是您的其他课程的样子:

Public class AnotherClass
    Private Shared blStop As Boolean = False

    'blablabla

    Public Shared Sub doTheLoop()
        While Not blStop
            'blablabla
        End While
    End Sub

    Public Shared Sub StopTheLoop()
        blStop = True
    End Sub

    'blablabla
End Class

然后你可以像这样调用这个循环:

'Form class
Private Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
    'You must run the loop on another thread or you will block the UI thread. 
    'Therefore your application will 'Stop Responding'
    System.Threading.Thread.QueueWorkUserItem(AddressOf(AnotherClass.DoTheLoop))
End Sub

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
    AnotherClass.StopTheLoop()
End Sub