Take the 2-minute tour ×

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


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

share|improve this question
add comment

2 Answers

up vote 82 down vote accepted

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)



Then on your Close event do:

keepLoopAlive = False

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.

share|improve this answer
Thanks! I ended implementing this into my program and it works great! I was originally asking if I could abruptly end the form process without having to specifically exit the loop but it sounds like this isn't possible. –  Phil Jan 24 '11 at 4:08
You can end the process without killing the loop. There are at least three easy ways in .Net: set "IsBackground" on the thread to "true" and then terminate all the foreground threads, or call Environment.FailFast() or Environment.Exit(). –  codekaizen Jan 24 '11 at 7:00
For all Googlers: Keep in mind that the correct way is to use the Background worker. –  George Stocker Jan 24 '11 at 13:40
Also, be aware that Microsoft cautions in the docs that the use of DoEvents can lead to hard to detect bugs and it is preferable to use multithreading instead. msdn.microsoft.com/en-us/library/… –  ho1 Jan 24 '11 at 16:23
add comment

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.

share|improve this answer
add comment

protected by Will Jan 24 '11 at 14:05

