7 Replies
I'm just pressing F5 to run this but Ideally the deconstructor should be called when GC.Collect executes but in my console window. I don't see it
generally speaking you should not rely on finalizers, but use the dispose pattern instead https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
Implement a Dispose method
In this article, learn to implement the Dispose method, which releases unmanaged resources used by your code in .NET.
@ramji it seems you just have to move the garbage collection outside of its scope, and add a little delay to give the finalizer thread enough time to finish it's work:
this works as expected
there is also
GC.WaitForPendingFinalizers()
to make it not as hardcodedFinalizers are not run immediately after they are collected
if the GC finds an object that has a finalizer & is not referenced anywhere, the object with the finalizer is put on a finalization queue to have its resource cleaned up then unallocated... eventually
there is no guarantees on when the finalizer will run
which is why you should avoid relying solely on finalizers, and use
Dispose()
patterns instead; the resource clean-ups are deterministic this way (because you do the clean-up yourself)
also rarely is there a need to write finalizers yourself. You should never write your own unless you are doing the unmanaged resource management yourselfFinalizers are not guaranteed to run, ever, no matter what you do
ericlippert
Fabulous adventures in coding
When everything you know is wrong, part one
Finalizers are interesting and dangerous because they are an environment in which everything you know is wrong. I’ve written a lot about the perils of C# finalizers / destructors (either name…
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.