This article is extracted from page 7 of the lesson for chapter 7 of the About Visual Basic "Complete Course" for VB.NET. Sign up for the entire course at ... this signup page.
The text book that is used in the About Visual Basic Complete Course has a just a few brief comments about infinite loops (called Endless Loops in the Book), but the subject deserves a lot more attention. They can be tricky and subtle, especially when the program statements inside the loop change the value that determines when the loop ends.
Consider this simple code:
Dim MyNumber As Integer
For MyNumber = 1 To 10
MyNumber -= 1
If you run this code, your computer will slow to a near stop because the program enters a very tight infinite loop. This one is easy to see, but what if the For ... Next loop was spread over about ten pages of code and MyNumber was changed in a lot of statements sprinkled throughout the ten pages? It might be a lot harder to figure out! So ... be very careful about this. It's easier to make a mistake here than you might think!
The key information that the book leaves outis what to do if you happen to code one of these little nasties by mistake. Your program is looping out of control and doing anything takes a long time.
Never fear! Assuming you're using Debug mode in Visual Studio .NET (this is what you should be using), simply click the Debug menu item and then select Stop Debugging. Your program will halt again!
(In a production program, you can open the Windows Task Manager and cancel the looping program.)
With that key information in mind (If you accept my challenge below, you're gonna need it!) -- here's a challenge: Code the most subtle infinite loop that you can think of and post the code in the About Visual Basic Forum! Please send an email@example.com emailto me if you code an entry so I don't overlook it. Periodically (that is, whenever I get the time), I'll look over the examples and if you code something really subtle and clever, I'll send you a free technical book! Extra points are given for:
- short programs (anyone can code something so long and detailed that it's hard to debug)
- programs where the infinite loop is hidden and can't be found
- programs that use common, ordinary VB.NET features rather than obscure ones
All entries are public and the decisions of the Guide (that's me) are final!