Reputation: 7242
This might be a really stupid question and im looking for your input if this is a bad/good/forbidden approach.
Lets just say i have a console application that i want to run forever.
I just tested this
Module Module1
Sub Main()
Try
Console.WriteLine(Now())
System.Threading.Thread.Sleep(1000)
Catch ex As Exception
End Try
' Call the routine again
Main()
End Sub
End Module
This simply prints the current time after sleeping 1 second and will continue to run.
I just want to know if this is a ok or bad way of looping a routine?
Upvotes: 2
Views: 600
Reputation: 9022
Running an infinite loop in a console app is definitely a bad idea. As Roger Rowland stated, it will result in a stack overflow.
If you want something to always be running in the background you could use a Windows Service instead of a console app.
If you need to use a console app, because Windows Services aren't available on all platforms (ie. Compact Framework), you could try this.
Upvotes: 1
Reputation: 942488
It depends on what machine you run this on. If it boots a 64-bit operating system and your project's Target CPU setting is "AnyCPU" then it will work okay, the 64-bit jitter will use an optimization called "tail recursion optimization" to turn the recursive call into a jump. If not then your program will eventually bomb with this web site's name.
No point in taking that risk when you can do this:
Sub Main()
Do
'' Rest of your code
''...
Loop
End Sub
Upvotes: 2
Reputation: 26279
This is infinite recursion and will eventually result in a stack overflow.
Every time you call a function, stuff is pushed on the stack. As each function finishes, the stack "unwinds" by popping that stuff off. You're never finishing any function and the stack has a limited size. Eventually you will exceed that size and you will crash.
Remove the sleep and see what happens.
Upvotes: 1