ASP.NET Basics, Part 4: Looping the Loop - The Infinite Loop and the Careless Coder
(Page 3 of 7 )
A word of caution to novice programmers (and careless experienced onesalso): if you fail to provide a valid condition to exit your loop, youwill get stuck in an infinite loop, one of the worst nightmares for adeveloper.
The likely symptom of this condition in the ASP.NET context is a serverthat fails to respond for an extended period of time while executing thescript. In such a situation, you can rest assured that an infinite loopis the most likely culprit. Don't take my word for it, try it foryourself (note that the following code deliberately introduces aninfinite loop for illustrative purposes, so use it at your own risk):
<script language="C#" runat="server">
void Page_Load()
{
// define a loop counter
int countdown= 10;
output.Text = "Beginning countdown...";
// repeat
while(countdown >= 0)
{
output.Text += "
" + countdown;
// don't change the loop counter, thereby introducing
// an infinite loop
// countdown--;
}
output.Text += "<h1>Houston, we have lift-off!</h1>";
}
</script>
<html>
<head><title>Countdown To Launch</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>
This example deliberately "forgets" to alter the value of the loopcounter every time the loop runs. As a result, the conditional testalways ends up true and the script never exits the "while" loop. Hence,the Web server continues to execute the script (and eat memory) tillsuch time as you forcibly terminate the script by shutting down theserver, or the server times out.
Since Web servers can't rely on a human being around 24/7 to monitor theserver and kill rogue scripts, most of them include built-in safeguardsto ensure that such rogue scripts do not completely take over systemresources. They do this by including a timeout period, which specifiesthe maximum amount of time given to a particular script to completeexecution. If the script exceeds this time limit, the Web server willautomatically halt further execution of the script and return an error.For the IIS server, you can modify this value using the Internet ServiceManager; read more about this at
http://www.microsoft.com/windows2000/en/server/iis/htm/core/iipy_32.htm.
Note, however, that just because the Web server has this built-intimeout capability, it is not an excuse for you, the developer, to writesloppy code; until the server timeout is activated, other requests willbe queued unnecessarily, affecting the performance of the server andannoying your users. Therefore, it is important to always ensure thatyour loop has a valid exit condition...because prevention is better thancure!
Next: Dos and Don'ts >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire