61

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.

default locale
  • 13,035
  • 13
  • 56
  • 62
Phil
  • 513
  • 1
  • 4
  • 5

2 Answers2

84

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.

Panafe
  • 346
  • 4
  • 6
  • 1
    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 04:08
  • 1
    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 07:00
  • 48
    For all Googlers: Keep in mind that the correct way is to use the Background worker. – George Stocker Jan 24 '11 at 13:40
  • 26
    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. http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx – Hans Olsson Jan 24 '11 at 16:23
12

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Craig
  • 129
  • 2