Consider the following C# program, I submitted it on codegolf as an answer to create a loop without looping:
class P{ static int x=0; ~P(){ System.Console.WriteLine(++x); new P(); } static void Main(){ new P(); } }
This program looks like an infinite loop in my inspection, but it seems to run for several thousand iterations, and then the program terminates successfully without error (No errors are thrown). Is it a spec violation that the finalizer for P
eventually is not called?
Clearly this is stupid code, that should never appear, but I am curious as to how the program could ever complete.
Original code golf post:: https://codegolf.stackexchange.com/questions/33196/loop-without-looping/33218#33218
An infinite loop can stop because of the memory if the memory grows in the loop. In this case, there is no memory grow. But, if you create some new heavy objects in every iteration of the loop, then it will stop eventually due to a Memory Limit Exception.
System. GC. Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.
As per Richter in the second edition of CLR via C# (yes I need to update):
Page 478
For (The CLR is shutting down) each Finalize method is given approximately two seconds to return. If a Finalize method doesn't return within two seconds, the CLR just kills the process - no more Finalize methods are called. Also, if it takes more then 40 seconds to call all objects' Finalize methods, again, the CLR just kills the process.
Also, as Servy mentions, it has its own thread.
The finalizer doesn't run in the main thread. The finalizer has its own thread that runs code, and it's not a foreground thread that would keep the application running. The main thread completes effectively right away, at which point the finalizer thread simply runs as many times as it gets a chance to before the process gets torn down. Nothing is keeping the program alive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With