Reputation: 370
I have a loop (in another class) what I want stop when I press a button, but I don't know how to do it
This is my code:
'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
Upvotes: 1
Views: 1287
Reputation: 4796
Here is how your other class should look like :
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
Then you can call this loop like this :
'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
Upvotes: 1
Reputation: 27322
your issue is this:
Public Sub doTheLoop(blStop as Boolean)
While (blStop = False)
'blablabla
End While
End Sub
The declaration of blStop, creates a new variable, so when you set, the value to False, you only set the one decalred locally.
A quick and dirty fix would be to declare the boolean ByRef
- that would mean that it will still reference the original variable.
Public Sub doTheLoop(ByRef blStop as Boolean)
While (blStop = False)
'blablabla
End While
End Sub
A better solution would be to have a method in your class that you call when you want to stop rather than passing round variables.
Upvotes: 1