Static instance, desctructor never called
-
22-08-2019 - |
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
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...
OTHER TIPS
Objects referenced by static fields are always reachable (assuming no class unloading or any other GC funkiness) and will never be collected.
Even though you might expect the finalizer on static objects to run when the process is shutdown, there are no guarantees there either:
- http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx (look at the section titled "V1 & V1.1 Finalization Guarantees"). I'm not sure how much of this has changed in .NET 2.0 or later.
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.