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