Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET - Interrupt form loop and end form

I have a form that goes through an endless loop and processes data. When I click a button that "closes" the form, the form keeps processing even though it is closed. I want the form to completely end and exit out of its loop statement, and then open a new form.

Here is the code I am using to close the form

frmMain.Close()
frmMain.Dispose()

Note: I am not using threads it's just a simple VB.NET application. I am not closing the main startup form.

like image 374
Phil Avatar asked Jan 23 '11 08:01

Phil


2 Answers

The "correct" way of doing this is with background worker threads really. But this will also work without the need of background worker threads.

Declare a variable in the form class.

Private keepLoopAlive As Boolean

Then write your processing loop to be something like:

keepLoopAlive = True

Do While keepLoopAlive 

    (your code that loops here)

    DoEvents

Loop

Then on your Close event do:

keepLoopAlive = False
Me.Close()

This will cause the loop to end first chance it gets, and your form should close.

Please note I've written this code from memory and not in an IDE so there may be typos.

like image 170
Panafe Avatar answered Oct 14 '22 21:10

Panafe


I am not a .NET developer so this may not be valid, but if I were performing an infinite loop, I would be checking each time I started that the loop was still valid with some sort of boolean value, and if it failed, drop out of the loop.

When you close the form, set the boolean value false and it will drop out, and you can either have an outer loop that waits and restarts the loop, or you can restart the entire function some other time.

like image 21
Craig Avatar answered Oct 14 '22 20:10

Craig