Tutorial :Static instance, desctructor never called



Question:

Please see code below. The destructors are never called. Anyone know why and how this can be rectified?

public partial class Form1 : Form  {      private Goo goo;        public Form1()      {          InitializeComponent();            goo = Goo.GetInstance();               }  }    public class Goo  {      private foo f = new foo();      private static Goo goo;      private Goo()      {}        public static Goo GetInstance()      {          if(goo!=null)          {              goo = new Goo();          }          return goo;      }        ~Goo()      {        }  }    class foo  {      ~foo()      {        }  }  


Solution:1

Objects referenced by static fields are not simply finalized unless you clear (set to null) the field - and even then it is non-deterministic and not guaranteed. Static fields count as root objects.

When (and why) would you expect this to be collected/finalized? It is still accessible...


Solution:2

Objects referenced by static fields are always reachable (assuming no class unloading or any other GC funkiness) and will never be collected.


Solution:3

Even though you might expect the finalizer on static objects to run when the process is shutdown, there are no guarantees there either:


Solution:4

That's not a destructor. It's a finalizer. That's a different thing. As the other two have said, because this is a static, it will never be collected, hence the finalizer will never run.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »