Created
November 7, 2015 20:41
-
-
Save ig-sinicyn/1488857d22c2d07c753d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
namespace ConsoleApplication1 | |
{ | |
internal class Program | |
{ | |
private class A | |
{ | |
~A() | |
{ | |
Console.WriteLine(" Finalizer called;"); | |
} | |
} | |
// IMPORTANT: run release build without debugging (Ctrl-F5 to launch) | |
private static void Main() | |
{ | |
var x = new A(); | |
var r = new WeakReference(x); | |
GC.Collect(); | |
GC.Collect(); | |
Console.WriteLine("object at gc gen" + GC.GetGeneration(x)); | |
GC.KeepAlive(x); | |
// x is available for collection now; | |
Console.WriteLine("before GC0, alive? " + r.IsAlive); | |
GC.Collect(0); | |
Console.WriteLine("before GC1, alive? " + r.IsAlive); | |
GC.Collect(1); | |
Console.WriteLine("before GC2, alive? " + r.IsAlive); | |
GC.Collect(2); | |
Console.WriteLine("after GC2, alive? " + r.IsAlive); | |
Thread.Sleep(500); | |
Console.WriteLine("After 500ms idle"); | |
GC.WaitForPendingFinalizers(); | |
Console.WriteLine("Done"); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment