Search code examples
c#.netgarbage-collectionfinalizer

.NET GC of unreferenced objects with static members


So I'm curious, will GC - and especially finalization - occur on an instance x in .NET when:

  • x is not referenced by anything
  • x has a static DbConnection property
  • y is an instance of the same class as x
  • y is still referenced by something

It strikes me that in this event, x could be declared dead by external references - but executing finalization on it may cause the DbConnection to be disposed while y still needs and holds a reference to it.

So which is it, in the scenario I described, is x collected? Does it get finalized? Or do all instances of it's type need to orphan in the heap before any one of them is collected? Will finalization happen across each instance?

I would think so, is the general rule to be followed just: Never touch a static or otherwise shared object in your finalizers?


Solution

  • Yes, the x instance would be eligible for GC. The DbConnection, since it is static, is completely unrelated to the instances in this case, and not relevant for determining whether the object is eligible for GC. It will not get collected as long as the static property holds a reference.

    Never touch a static or otherwise shared object in your finalizers?

    This is typically a good call. In general, you should never write finalizers for your managed types, unless they're wrapping unmanaged resources, at which point the type should do nothing but manage that resource (ideally). Even then, using SafeHandle is often a better approach when possible.