Skip to content

Instantly share code, notes, and snippets.

@iamdroppy
Created August 17, 2018 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamdroppy/ddef0a8b1cee23f0d47d35abd9828a10 to your computer and use it in GitHub Desktop.
Save iamdroppy/ddef0a8b1cee23f0d47d35abd9828a10 to your computer and use it in GitHub Desktop.
GC in .NET example
/*
This is an example of GC in C#, how it works, and how it does not work.
This is intended to end some debates how it handles things.
*/
// First of all, this is a common misconception: IDisposable.Dispose() DOESN'T dereference or collects the object in any way or form.
// Example:
class Test : IDisposable
{
public void RunTest()
{
Console.WriteLine("I'm alive");
}
public void Dispose()
{
}
}
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.RunTest();
test.Dispose();
test.RunTest();
Console.ReadKey();
}
}
/*
Result:
I'm alive
I'm alive
*/
// As you can see, nothing happened.
// Now, let's make some changes, and make a Timer inside the method, call Dispose, and then set object reference to null.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GCExample
{
class Test : IDisposable
{
public Test()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.Interval += 1000;
timer.Start();
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("I'm still alive");
}
public void Dispose()
{
Console.WriteLine("Called our IDisposable.Dispose.");
}
}
class Program
{
static void Test()
{
Test test2 = new Test();
test2.Dispose();
test2 = null;
}
static void Main(string[] args)
{
Test();
GC.Collect();
Console.ReadKey();
}
}
}
/*
Result (same happens if you are using the 'using' keyword):
Started test.
Called our IDisposable.Dispose.
I'm still alive
I'm still alive
I'm still alive
I'm still alive
I'm still alive
...*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment