Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An Example of forced GC gone bad?

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.

like image 801
Rikon Avatar asked Jul 23 '12 19:07

Rikon


2 Answers

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#.

like image 121
James Avatar answered Oct 07 '22 21:10

James


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.

like image 30
usr Avatar answered Oct 07 '22 20:10

usr