A garbage collector is not an active system. It runs "sometimes" and mostly on demand (for instance when all pages offered by the OS are full).
Most garbage collectors run in a breadth-first generation-like manner in a subthread. In most cases it can take hours before the object is recycled.
The only problem occurs when you want to terminate the program. However that's not really a problem. When you use kill
an OS will ask politely to terminate processes. When the process however remains active, one can use kill -9
where the Operating System removes all control.
When I ran your code in the interactive csharp
environment, I've got:
csharp>
1
2
Unhandled Exception:
System.NotSupportedException: Stream does not support writing
at System.IO.FileStream.Write (System.Byte[] array, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.FlushBytes () [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.FlushCore () [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.Write (System.Char[] buffer, Int32 index, Int32 count) [0x00000] in <filename unknown>:0
at System.IO.CStreamWriter.Write (System.Char[] buffer, Int32 index, Int32 count) [0x00000] in <filename unknown>:0
at System.IO.CStreamWriter.Write (System.Char[] val) [0x00000] in <filename unknown>:0
at System.IO.CStreamWriter.Write (System.String val) [0x00000] in <filename unknown>:0
at System.IO.TextWriter.Write (Int32 value) [0x00000] in <filename unknown>:0
at System.IO.TextWriter.WriteLine (Int32 value) [0x00000] in <filename unknown>:0
at System.IO.SynchronizedWriter.WriteLine (Int32 value) [0x00000] in <filename unknown>:0
at System.Console.WriteLine (Int32 value) [0x00000] in <filename unknown>:0
at P.Finalize () [0x00000] in <filename unknown>:0
Thus your program crashes because stdout
is blocked by the termintation of the environment.
When removing the Console.WriteLine
and killing the program. It after five second the program terminates (in other words, the garbage collector gives up and simply will free all memory without taking finalizers into account).