When GC.KeepAlive Doesn’t

The purpose of GC.KeepAlive(Object) is to tell the GC not to collect an object until a certain point.  For example: class MyObject{   ~MyObject()   {   Console.WriteLine(“MyObject Finalized”);   }                 public static void Main()   {      MyObject obj = new MyObject();      LongRunningMethod();      GC.KeepAlive(obj); // ~MyObject will NOT be run before this call      …   }} KeepAlive will ensure ~MyObject will not get run before LongRunningMethod gets called.  This is useful…

6

WeakReferences And Tracking Resurrection

The WeakReference class has two public constructors.    public WeakReference(Object target) public WeakReference(Object target, bool trackResurrection)   The first parameter is pretty obvious.  It’s the object you want the WeakReference to reference, without keeping the object alive.  If a WeakReference is the only thing referencing an object, then the GC is free to collect the…

3

Object Resurrection

I’m sure many of you have heard the term “object resurrection” with respect to the GC.  It’s an interesting (but not very useful) way to illustrate object lifetimes and the role of finalization versus garbage collection.  Basically, it’s a way to reference an object that has been finalized.   Here’s a rough description of how…

3

Why You Shouldn’t Rely On WeakReference.IsAlive

The WeakReference class has the property IsAlive.  The problem with it, is that you can only trust it if it returns false.   While a WeakReference points to an object that is either live (reachable), or garbage (unreachable) that has not yet been collected by the GC, the IsAlive property will return true.  After an…

5