I’m doing an intro presentation on the .Net CLR GC and have all the various pieces, but I wanted an example specifically of how trying to force collection could be dangerous or harmful. I know you can force things into higher generations prematurely, but (from what I could tell) that would really only slow things down.
I’m trying to think of a situation where forcing GC could be truly damaging and I keep coming up w/ merely less efficient solutions.
Here’s an interesting demonstration. Note you should run this demo compiled in release mode or it may not work as advertised.
Version 1:
Version 1 will happily print the date and time to the text box once a second.
Version 2:
Now in Version 2, the date and time will only be printed once because, after the declaration, there are no more references to the timer object, and so the timer object gets collected.
That’s a fairly contrived example but may make for a good demonstration.
I must credit Jeffery Richter for this one – it’s in his excellent book
CLR via C#.