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:
private void Button_Click(object sender, EventArgs e)
{
Timer timer = new Timer(Print, null, 0, 1000);
}
private void Print(Object o)
{
if (textBox1.InvokeRequired)
{
Action<object> action = Print;
textBox1.Invoke(action, o);
return;
}
textBox1.Text = DateTime.Now.ToString();
}
Version 1 will happily print the date and time to the text box once a second.
Version 2:
private void Button_Click(object sender, EventArgs e)
{
Timer timer = new Timer(Print, null, 0, 1000);
}
private void Print(Object o)
{
if (textBox1.InvokeRequired)
{
Action<object> action = Print;
textBox1.Invoke(action, o);
return;
}
textBox1.Text = DateTime.Now.ToString();
GC.Collect(); // force a garbage collection
}
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#
.
What about the following, bad idea? "Let's force a GC after every HTTP request in ASP.NET in order to clean up request state which will surely be orphaned!"
That's a bad idea because concurrent HTTP request would interfere with each other. This would introduce lots of latency spikes and destroy performance. All that starting from an innocent "optimization".
That's about the worst I can think of.
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